本文整理汇总了Python中models.Report.save方法的典型用法代码示例。如果您正苦于以下问题:Python Report.save方法的具体用法?Python Report.save怎么用?Python Report.save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类models.Report
的用法示例。
在下文中一共展示了Report.save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_parse_report
# 需要导入模块: from models import Report [as 别名]
# 或者: from models.Report import save [as 别名]
def test_parse_report(self):
response = '''
{"response":[
{"clicks":"103","money":"1000.00","day":"2010-10-08","campaign_id":123,"client_id":123,"client_name":"Ford","campaign_name":"Campaign1","ctr":"0.199","impressions":"51635"}
]}
'''
account = Account.objects.create(remote_id=1)
Campaign.objects.create(account=account, remote_id=123, fetched=datetime.now())
Client.objects.create(account=account, remote_id=123, fetched=datetime.now())
instance = Report(time_from=datetime.now(), time_to=datetime.now())
instance.parse(json.loads(response)['response'][0])
instance.save()
self.assertTrue(isinstance(instance.campaign, Campaign))
self.assertEqual(instance.campaign.remote_id, 123)
self.assertTrue(isinstance(instance.client, Client))
self.assertEqual(instance.client.remote_id, 123)
self.assertEqual(instance.clicks, 103)
self.assertEqual(instance.impressions, 51635)
self.assertEqual(instance.day, date(2010,10,8))
self.assertEqual(instance.client_name, "Ford")
self.assertEqual(instance.campaign_name, "Campaign1")
self.assertEqual(instance.money, '1000.00')
self.assertEqual(instance.ctr, '0.199')
示例2: test_model_chart
# 需要导入模块: from models import Report [as 别名]
# 或者: from models.Report import save [as 别名]
def test_model_chart(self):
"Test Chart Model"
report = Report(name='test')
report.save()
obj = Chart(name='test', report=report)
obj.save()
self.assertEquals('test', obj.name)
self.assertNotEquals(obj.id, None)
obj.delete()
示例3: user_report
# 需要导入模块: from models import Report [as 别名]
# 或者: from models.Report import save [as 别名]
def user_report(request):
'''
report handle
'''
if request.method == "POST":
rep_id = request.POST.get("rep_id","")
rep_type = request.POST.get("rep_type","")
reason = request.POST.get("reason","")
if rep_id == '' or rep_type == '' or reason == '':
return HttpResponse(-3)
report = Report(rep_type=int(rep_type),beReported=rep_id,reason=reason)
report.save()
return HttpResponse(0)
示例4: addreport
# 需要导入模块: from models import Report [as 别名]
# 或者: from models.Report import save [as 别名]
def addreport(request):
if request.method == 'POST':
form = ReportForm(request.POST)
if form.is_valid():
report = Report()
report.headline = form.cleaned_data.get("headline")
report.content = form.cleaned_data.get("content")
report.reporter = request.user.username
report.date = datetime.now()
report.save()
return HttpResponseRedirect(reverse('news:index'))
else:
form = ReportForm()
return render_to_response('news/addreport.html', {'form':form}, context_instance=RequestContext(request))
示例5: save_b
# 需要导入模块: from models import Report [as 别名]
# 或者: from models.Report import save [as 别名]
def save_b(self):
''' add operation '''
# entete de la facture
if not self.table_buy.isvalid:
return False
owner = Owner.get(Owner.islog == True)
date = str(self.date.text())
values_t = self.table_buy.get_table_items()
buy = Buy()
# buy.date = datetime_
buy.provd_or_clt = \
ProviderOrClient.get_or_create(
"Fournisseur", 000000, ProviderOrClient.FSEUR)
buy.owner = owner
try:
buy.save()
err = False
except:
raise
raise_error(
"Erreur", u"Impossible d'enregistrer l'entête de la facture")
return False
for name, qty, cost_buying, selling_price in values_t:
rep = Report()
rep.buy = buy
rep.type_ = Report.E
rep.store = 1
rep.date = date_to_datetime(date)
rep.product = Product.get(name=name)
rep.qty = int(qty)
rep.cost_buying = int(cost_buying)
rep.selling_price = int(selling_price)
try:
rep.save()
except Exception as e:
print(e)
err = True
if err:
buy.delete_instance()
raise_error("Erreur", u"Ce mouvement n'a pas pu etre "
u"enregistré dans les rapports")
return False
else:
self.parent.Notify(u"L'entrée des articles avec succès", "success")
self.change_main_context(BuyShowViewWidget, buy=buy)
示例6: report
# 需要导入模块: from models import Report [as 别名]
# 或者: from models.Report import save [as 别名]
def report(request):
if request.method == 'POST':
errors = []
try:
patientId = int(request.POST.get('patientId'))
name = request.POST.get('name')
latitude = float(request.POST.get('latitude'))
longitude = float(request.POST.get('longitude'))
dt = request.POST.get('datetime')
datetime = datetime.strptime(dt,"%Y-%m-%d %H:%M:%S")
incomingReport = Report(patientId=patientId, name=name, \
latitude=latitude, longitude=longitude, datetime=datetime)
incomingReport.save()
return HttpResponse("Report successfully added to database")
except ValueError:
return HttpResponse("Report not added properly")
else:
raise Http404
示例7: log_report
# 需要导入模块: from models import Report [as 别名]
# 或者: from models.Report import save [as 别名]
def log_report(uri, data):
parts = data.strip().split("&")
form = {}
for part in parts:
if len(part) == 0:
continue
key, val = map(urllib.unquote_plus, part.split("="))
form[key] = form.get(key, '') + val
r = Report()
r.uri = uri
r.additional = form.get('a', '')
r.site_specific = form.get('site', '')
r.screen = form.get('s', '')
r.remote_ip = request.access_route[0]
r.headers = "\r\n".join(["%s: %s" % x for x in request.headers.to_list()])
r.url = form.get('u', '')
r.cookie = form.get('c', '')
r.useragent = form.get('ua', '')
r.save()
logging.error("Logged %s" % r)
示例8: add_report_to_cracker
# 需要导入模块: from models import Report [as 别名]
# 或者: from models.Report import save [as 别名]
def add_report_to_cracker(cracker, client_ip, when=None):
if when is None:
when = time.time()
reports = yield Report.find(
where=["cracker_id=? AND ip_address=?", cracker.id, client_ip],
orderby='latest_report_time ASC'
)
if len(reports) == 0:
report = Report(ip_address=client_ip, first_report_time=when, latest_report_time=when)
yield report.save()
cracker.current_reports += 1
yield report.cracker.set(cracker)
elif len(reports) == 1:
report = reports[0]
# Add second report after 24 hours
if when > report.latest_report_time + 24*3600:
report = Report(ip_address=client_ip, first_report_time=when, latest_report_time=when)
yield report.save()
yield report.cracker.set(cracker)
elif len(reports) == 2:
latest_report = reports[1]
# Add third report after again 24 hours
if when > latest_report.latest_report_time + 24*3600:
report = Report(ip_address=client_ip, first_report_time=when, latest_report_time=when)
yield report.save()
yield report.cracker.set(cracker)
else:
latest_report = reports[-1]
latest_report.latest_report_time = when
yield latest_report.save()
cracker.total_reports += 1
cracker.latest_time = when
cracker.resiliency = when - cracker.first_time
yield cracker.save()
示例9: cpanel_submit
# 需要导入模块: from models import Report [as 别名]
# 或者: from models.Report import save [as 别名]
def cpanel_submit(request):
# The user adding the request
user = request.user
name = request.POST['name']
phone = request.POST['phone']
email = request.POST['email']
type = request.POST['device']
os = request.POST['os']
problem = request.POST['problem']
description = request.POST['description']
deviceObj = Device()
report = Report()
usersWithSameEmail = User.objects.filter(email=email)
reportUser = User()
userFound = False
for u in usersWithSameEmail:
# If user exists, don't create a new one
if u.email == email:
reportUser = u
userFound = True
if not userFound:
reportUser.email = email
reportUser.username = name
reportUser.password = 'password'
reportUser.save()
# Get the devices the user has
usersDevices = Device.objects.filter(owner=reportUser)
deviceFound = False
for d in usersDevices:
# If the device exists recognize it, and use it
if d.os == os and d.type == type:
deviceObj = d
deviceFound = True
if not deviceFound:
# Generate device object
deviceObj.owner = reportUser
deviceObj.os = os
deviceObj.type = type
deviceObj.save()
# Generate Report
report.owner = reportUser
report.device = deviceObj
report.description = description
report.problem = problem
report.completed = False
report.save()
# Generate initial status
status = Status()
status.report = report
# Checked in message
status.message = 'c'
status.tech = user
status.save()
return cpanel(request, True)
示例10: test_model_report
# 需要导入模块: from models import Report [as 别名]
# 或者: from models.Report import save [as 别名]
def test_model_report(self):
obj = Report(name='test')
obj.save()
self.assertEquals('test', obj.name)
self.assertNotEquals(obj.id, None)
obj.delete()
示例11: ReportsViewsTest
# 需要导入模块: from models import Report [as 别名]
# 或者: from models.Report import save [as 别名]
class ReportsViewsTest(TestCase):
username = "test"
password = "password"
def setUp(self):
self.group, created = Group.objects.get_or_create(name='test')
self.user, created = DjangoUser.objects.get_or_create(username=self.username)
self.user.set_password(self.password)
self.user.save()
perspective, created = Perspective.objects.get_or_create(name='default')
perspective.set_default_user()
perspective.save()
ModuleSetting.set('default_perspective', perspective.id)
self.report = Report(name='test')
self.report.set_default_user()
self.report.save()
self.chart = Chart(name='test_chart', report=self.report)
self.chart.set_default_user()
self.chart.save()
######################################
# Testing views when user is logged in
######################################
def test_reports_login(self):
"""Testing /reports/"""
response = self.client.post('/accounts/login',
{'username': self.username, 'password': self.password})
self.assertRedirects(response, '/')
response = self.client.get(reverse('reports'))
self.assertEquals(response.status_code, 200)
def test_index_login(self):
"Testing /reports/index/"
response = self.client.post('/accounts/login',
{'username': self.username, 'password': self.password})
self.assertRedirects(response, '/')
response = self.client.get(reverse('reports_index'))
self.assertEquals(response.status_code, 200)
def test_index_owned(self):
"Testing /reports/owned/"
response = self.client.post('/accounts/login',
{'username': self.username, 'password': self.password})
self.assertRedirects(response, '/')
response = self.client.get(reverse('reports_index'))
self.assertEquals(response.status_code, 200)
# Charts
def test_chart_add(self):
"Testing /reports/chart/add/"
response = self.client.post('/accounts/login',
{'username': self.username, 'password': self.password})
self.assertRedirects(response, '/')
response = self.client.get(reverse('reports_chart_add'))
self.assertEquals(response.status_code, 200)
def test_chart_delete_login(self):
"Testing /reports/chart/delete/<chart_id>"
response = self.client.post('/accounts/login',
{'username': self.username, 'password': self.password})
self.assertRedirects(response, '/')
response = self.client.get(
reverse('reports_chart_delete', args=[self.chart.id]))
self.assertEquals(response.status_code, 200)
# Reports
def test_report_add(self):
"Testing /reports/report/add/"
response = self.client.post('/accounts/login',
{'username': self.username, 'password': self.password})
self.assertRedirects(response, '/')
response = self.client.get(reverse('reports_report_add'))
self.assertEquals(response.status_code, 200)
def test_report_delete_login(self):
"Testing /reports/report/delete/<report_id>"
response = self.client.post('/accounts/login',
{'username': self.username, 'password': self.password})
self.assertRedirects(response, '/')
response = self.client.get(
reverse('reports_report_delete', args=[self.report.id]))
self.assertEquals(response.status_code, 200)
######################################
# Testing views when user is not logged in
######################################
def test_reports_out(self):
"Testing /reports/"
response = self.client.get(reverse('reports'))
self.assertRedirects(response, reverse('user_login'))
def test_index_out(self):
"Testing /reports/index/"
response = self.client.get(reverse('reports_index'))
self.assertRedirects(response, reverse('user_login'))
def test_index_owned_out(self):
"Testing /reports/owned/"
#.........这里部分代码省略.........
示例12: save_b
# 需要导入模块: from models import Report [as 别名]
# 或者: from models.Report import save [as 别名]
def save_b(self):
''' add operation '''
# entete de la facture
print("save")
if not self.is_valide():
return
invoice_date = unicode(self.invoice_date.text())
num_invoice = int(self.num_invoice.text())
invoice_type = self.liste_type_invoice[
self.box_type_inv.currentIndex()]
lis_error = []
invoice = Invoice()
try:
self.owner = Owner.get(Owner.islog == True)
except:
lis_error.append("Aucun utilisateur est connecté <br/>")
paid_amount = int(self.table_invoice.paid_amount_field.text())
try:
clt = ProviderOrClient.get_or_create(
self.name_client, int(self.phone.replace(" ", "")), ProviderOrClient.CLT)
except ValueError:
field_error(
self.name_client_field, "Nom, numéro de téléphone du client")
invoice.number = num_invoice
invoice.owner = self.owner
invoice.client = clt
invoice.location = "Bamako"
invoice.type_ = invoice_type
invoice.subject = ""
invoice.paid_amount = paid_amount
invoice.tax = False
try:
invoice.save()
if int(paid_amount) != 0 or invoice_type == Invoice.TYPE_BON:
Refund(type_=Refund.DT, owner=self.owner, amount=paid_amount,
date=date_to_datetime(invoice_date), provider_client=clt,
invoice=Invoice.get(number=num_invoice)).save()
except Exception as e:
invoice.deletes_data()
lis_error.append(
"Erreur sur l'enregistrement d'entête de facture<br/>")
return False
# Save invoiceitems
invoice = Invoice.get(Invoice.number == num_invoice)
for name, qty, price in self.table_invoice.get_table_items():
rep = Report()
product = Product.get(Product.name == name)
rep.store = 1
rep.product = product
rep.invoice = invoice
rep.type_ = Report.S
rep.cost_buying = int(product.last_report.cost_buying)
rep.date = date_to_datetime(invoice_date)
rep.qty = int(qty)
rep.selling_price = int(price)
try:
rep.save()
except Exception as e:
lis_error.append(e)
if lis_error != []:
invoice.delete_instance()
self.parent.Notify(lis_error, "error")
return False
else:
self.parent.Notify("Facture Enregistrée avec succès", "success")
self.change_main_context(ShowInvoiceViewWidget,
invoice_num=invoice.number)
示例13: Report
# 需要导入模块: from models import Report [as 别名]
# 或者: from models.Report import save [as 别名]
value = (s[l/2 - 1] + s[l/2]) / 2
metric['value'] = value
report = Report(system=system, date=date)
filename = system_name + "-" + date.strftime("%Y%m%d-%H%M%S") + ".gz"
str_io = StringIO()
gz = GzipFile(filename, mode="wb", fileobj=str_io)
gz.write(reportContents.encode("UTF-8"))
gz.close()
# so just compress into a memory buffer and save that.
report.upload.save(filename,
ContentFile(str_io.getvalue()))
report.save()
for name in metrics:
metric = metrics[name]
description = metric['description']
units = metric['units']
value = metric['value']
storedMetric = Metric(name=name,
description=description,
units=units,
report=report,
value=value)
storedMetric.save()
示例14: report_add
# 需要导入模块: from models import Report [as 别名]
# 或者: from models.Report import save [as 别名]
def report_add(request, response_format='html'):
"Create new report based on user choice"
if 'report' in request.POST:
report_id = request.POST['report']
return HttpResponseRedirect(reverse('reports_report_edit', args=[report_id]))
# FIRST TIME AN OBJECT IS CHOSEN
if 'choice' in request.POST:
form = None
object = request.POST['choice']
object = str(
object.replace("{'object_type': u'", '').replace("'}", ''))
full_object = object
object = object.split('.', 3)
module_name = object[0] + '.' + object[1] + '.' + object[2]
import_name = object[3]
module = __import__(
module_name, globals(), locals(), [import_name], -1)
classobj = getattr(module, import_name)
obj = classobj()
names = obj.get_field_names()
fields = []
for name in names:
fields.append(Field(name=name, display=True))
model = Model(full_object, fields)
report = Report()
report.name = "Untitled {0!s} Report".format((obj._meta.object_name))
report.model = dumps(model)
report.creator = request.user.profile
report.save()
return HttpResponseRedirect(reverse('reports_report_edit', args=[report.id]))
# Initial Object Type Choice
user_modules = [mod.name for mod in request.user.profile.get_perspective().get_modules()]
modules = [mod.name for mod in Module.objects.all()]
query = Q(object_type__contains="core")
for module in modules:
if module not in user_modules:
query = query | Q(object_type__contains=module)
object_types = list(Object.objects.all().exclude(query).values(
'object_type').distinct().order_by('object_type'))
object_names = []
for object_type in object_types:
module_name = _get_module_name(object_type['object_type'])
human_type = Object.objects.filter(
object_type=object_type['object_type'])[0].get_human_type()
object_names.append("{0!s}: {1!s}".format(module_name, human_type))
form = ObjChoiceForm(request.user, object_types=object_types, object_names=object_names)
return render_to_response('reports/report_add', {'form': form}, context_instance=RequestContext(request),
response_format=response_format)
示例15: default
# 需要导入模块: from models import Report [as 别名]
# 或者: from models.Report import save [as 别名]
def default(request):
applicationFolder = getApplicationFolder()
#if the request is POST -> file is being uploaded
if str(request.method).lower() == 'post':
form = UploadFileForm(request.POST, request.FILES)
#if there is file for uploading
if form.is_valid():
#uplaod the file on the server
tarPath = handle_uploaded_file(request.FILES['file'])
reportMetaData = {}
#here check it could be zip or tar.gz
isTar = (tarPath.endswith('tar.gz') or tarPath.endswith('tgz'))
isZip = tarPath.endswith('.zip')
#get metadata depending on the archive
if isTar:
reportMetaData = getReportMetadataTar(tarPath)
elif isZip:
reportMetaData = getReportMetadataZip(tarPath)
#create new Report object set its metadata and save it
report = Report()
report.username = reportMetaData['user']
report.ganga_version = reportMetaData['version']
report.job_uuid = reportMetaData['uuid']
report.date_uploaded = datetime.now()
report.save()
#save the report's mon links
monlinks = reportMetaData['monlinks']
for key, value in monlinks.items():
monlink = MonitoringLink()
monlink.report = report
monlink.monitoring_link_name = key
monlink.monitoring_link_path = value
monlink.save()
#rename the uploaded file on the server with the report id
if isTar:
rename_file(tarPath, report.id, 'tar')
elif isZip:
rename_file(tarPath, report.id, 'zip')
#sets the download path that will be shown to the user
serverDownloadPath = os.path.join(settings.SERVER_DOWNLOAD_PATH, str(report.id))
community, debug = getCommunityAndDebugMode()[0], getCommunityAndDebugMode()[1]
if community == 'CMS' and debug == False :
#because for CMS there is different DNS
serverDownloadPath = os.path.join(settings_HOST+"cmserrorreports/download", str(report.id))
elif community == 'CMS':
serverDownloadPath = serverDownloadPath.replace('errorreports', 'cmserrorreports')
renderToResponse = render_to_response('%s/upload.html' % applicationFolder, {'form': form, 'path': serverDownloadPath }, context_instance = RequestContext(request))
logServerResponse(str(renderToResponse))
return renderToResponse
else:
errors=""
for key, value in form.errors.iteritems():
errors += str(key) + ": "
for i in value:
errors += str(i) + ", "
errors += " "
return render_to_response('%s/upload.html' % applicationFolder, {'form': form, 'path' : 'invalid form: %s' % errors }, context_instance = RequestContext(request))
else:
#user = User.objects.create_user('gosho', '[email protected]', 'gosho')
#user.save()
form = UploadFileForm()
return render_to_response('%s/upload.html' % applicationFolder, { 'form' : form, 'path' : 'Method: %s' % request.method }, context_instance = RequestContext(request))