本文整理匯總了Python中django.http.HttpResponse方法的典型用法代碼示例。如果您正苦於以下問題:Python http.HttpResponse方法的具體用法?Python http.HttpResponse怎麽用?Python http.HttpResponse使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.http
的用法示例。
在下文中一共展示了http.HttpResponse方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponse [as 別名]
def get(self, request, *args, **kwargs):
self.object = self.get_object()
if settings.DOCUMENTS_USE_X_ACCEL_REDIRECT:
response = HttpResponse()
response["X-Accel-Redirect"] = self.object.file.url
# delete content-type to allow Gondor to determine the filetype and
# we definitely don't want Django's crappy default :-)
del response["content-type"]
else:
# Note:
#
# The 'django.views.static.py' docstring states:
#
# Views and functions for serving static files. These are only to be used
# during development, and SHOULD NOT be used in a production setting.
#
response = static.serve(request, self.object.file.name,
document_root=settings.MEDIA_ROOT)
return response
示例2: test_download
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponse [as 別名]
def test_download(self):
"""
Ensure the requested Document file is served.
"""
simple_file = SimpleUploadedFile("delicious.txt", self.file_contents)
document = Document.objects.create(name="Honeycrisp",
author=self.user,
file=simple_file,
)
document.save()
with self.login(self.user):
# Verify `django.views.static.serve` is called to serve up the file.
# See related note in .views.DocumentDownload.get().
with mock.patch("django.views.static.serve") as serve:
serve.return_value = HttpResponse()
self.get_check_200(self.download_urlname, pk=document.pk)
self.assertTrue(serve.called)
示例3: filter
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponse [as 別名]
def filter(request):
"""
Search for customers by name
May return JSON for ajax requests
or a rendered list
"""
import json
from django.http import HttpResponse
if request.method == "GET":
results = list()
query = request.GET.get("query")
customers = Customer.objects.filter(fullname__icontains=query)
for c in customers:
results.append(u"%s <%s>" % (c.name, c.email))
results.append(u"%s <%s>" % (c.name, c.phone))
else:
query = request.POST.get("name")
results = Customer.objects.filter(fullname__icontains=query)
data = {'results': results, 'id': request.POST['id']}
return render(request, "customers/search-results.html", data)
return HttpResponse(json.dumps(results), content_type="application/json")
示例4: render_to_response
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponse [as 別名]
def render_to_response(self, context, **response_kwargs):
out = {
'order': self.object.code,
'status': self.object.get_status_name(),
'status_description': self.object.get_status_description(),
}
if Configuration.conf('checkin_timeline'):
timeline = []
for i in self.object.orderstatus_set.exclude(status=None):
status = {'badge': i.get_badge()}
status['status'] = i.status.title
status['started_at'] = i.started_at.isoformat()
status['description'] = i.status.description
timeline.append(status)
out['timeline'] = timeline
return HttpResponse(json.dumps(out), content_type='application/json')
示例5: download_results
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponse [as 別名]
def download_results(request):
import csv
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="orders.csv"'
writer = csv.writer(response)
header = [
'CODE',
'CUSTOMER',
'CREATED_AT',
'ASSIGNED_TO',
'CHECKED_IN',
'LOCATION'
]
writer.writerow(header)
for o in request.session['order_queryset']:
row = [o.code, o.customer, o.created_at,
o.user, o.checkin_location, o.location]
coded = [unicode(s).encode('utf-8') for s in row]
writer.writerow(coded)
return response
示例6: toggle_flag
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponse [as 別名]
def toggle_flag(request, kind, pk, flag):
"""
Toggles a flag of a note (read/unread, flagged/not, reported/not)
"""
if kind == 'articles':
note = get_object_or_404(Article, pk=pk)
if flag == 'flagged':
note.toggle_flagged(request.user)
return HttpResponse(note.get_flagged_title(request.user))
if flag == 'read':
note.toggle_read(request.user)
return HttpResponse(note.get_read_title(request.user))
field = 'is_%s' % flag
note = get_object_or_404(Note, pk=pk)
attr = getattr(note, field)
setattr(note, field, not attr)
note.save()
return HttpResponse(getattr(note, 'get_%s_title' % flag)())
示例7: get
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponse [as 別名]
def get(self, request, *args, **kwargs):
site = Site.find_for_request(request)
if not site:
raise Http404
if request.resolver_match.url_name == 'entry_page_serve_slug':
# Splitting the request path and obtaining the path_components
# this way allows you to place the blog at the level you want on
# your sitemap.
# Example:
# splited_path = ['es', 'blog', '2016', '06', '23', 'blog-entry']
# slicing this way you obtain:
# path_components = ['es', 'blog', 'blog-entry']
# with the oldest solution you'll get ['es', 'blog-entry']
# and a 404 will be raised
splited_path = strip_prefix_and_ending_slash(request.path).split("/")
path_components = splited_path[:-4] + splited_path[-1:]
else:
path_components = [strip_prefix_and_ending_slash(request.path).split('/')[-1]]
page, args, kwargs = site.root_page.specific.route(request, path_components)
for fn in hooks.get_hooks('before_serve_page'):
result = fn(page, request, args, kwargs)
if isinstance(result, HttpResponse):
return result
return page.serve(request, *args, **kwargs)
示例8: doUpvote
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponse [as 別名]
def doUpvote(request):
'''點讚接口'''
try:
id=request.GET.get('id',None)
userID = request.GET.get('userID', None)
if id == None:
return HttpResponse('請提供 id 參數!')
Articles().updateUpvote(id=id)
res = {
'msg' : '點讚成功!',
'result' : True,
}
article = Articles().find_one(id=id)
# 更新用戶label,個性化推薦用 點讚暫定+10
if userID != None:
Users().update_label(userID, article['category'], 10)
except Exception,e:
res = {
'msg' : '點讚失敗!',
'reason' : str(e),
'result' : False,
}
示例9: get
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponse [as 別名]
def get(self, request, *args, **kwargs):
content_type = self.determine_content_type(request)
handlers = self.content_handlers()
handler = handlers[str(content_type)]
response = HttpResponse(json.dumps(handler(self)), content_type)
patch_vary_headers(response, ['Accept'])
if self.cache_max_age is not None:
patch_cache_control(response, max_age=self.cache_max_age)
if str(content_type) == 'application/json':
# Add a Link header
can_embed_relation = lambda relation: not self.can_embed(relation[0])
relations = filter(can_embed_relation, self.get_relations().items())
relation_to_link = lambda relation: '<{}>; rel="{}"'.format(relation[1].get_uri(), relation[0])
links = list(map(relation_to_link, relations))
if len(links) > 0:
response['Link'] = ', '.join(links)
if str(content_type) != 'application/vnd.siren+json':
# Add an Allow header
methods = ['HEAD', 'GET'] + list(map(lambda a: a.method, self.get_actions().values()))
response['allow'] = ', '.join(methods)
return response
示例10: admin_handler
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponse [as 別名]
def admin_handler(request):
""" HTTP Request handler function to handle actions on yang modules """
if not request.user.is_authenticated():
return HttpResponse(Response.error(None, 'User must be logged in'))
if request.method != 'GET':
return HttpResponse(Response.error(None, 'Invalid admin Request'))
action = request.GET.get('action', '')
logger.info('Received admin request %s for user %s' % (action, request.user.username))
if action in ['subscribe', 'unsubscribe', 'delete', 'graph']:
payload = request.GET.get('payload', None)
print(str(payload))
(rc, msg) = ModuleAdmin.admin_action(request.user.username, payload, action)
if not rc:
return HttpResponse(Response.error(action, msg))
if action == 'graph':
return HttpResponse(Response.success(action, msg))
modules = ModuleAdmin.get_modules(request.user.username)
return HttpResponse(Response.success(action, 'ok', xml=modules))
示例11: cif
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponse [as 別名]
def cif(request, sid):
client = Client(headers=get_consumer(request)) # sets/returns global variable
cif = client.structures.get_entry(pk=sid, _fields=["cif"]).result()["cif"]
if cif:
response = HttpResponse(cif, content_type="text/plain")
response["Content-Disposition"] = "attachment; filename={}.cif".format(sid)
return response
return HttpResponse(status=404)
示例12: download_json
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponse [as 別名]
def download_json(request, cid):
client = Client(headers=get_consumer(request)) # sets/returns global variable
contrib = client.contributions.get_entry(pk=cid, fields=["_all"]).result()
if contrib:
jcontrib = json.dumps(contrib)
response = HttpResponse(jcontrib, content_type="application/json")
response["Content-Disposition"] = "attachment; filename={}.json".format(cid)
return response
return HttpResponse(status=404)
示例13: csv
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponse [as 別名]
def csv(request, project):
from pandas import DataFrame
from pandas.io.json._normalize import nested_to_record
client = Client(headers=get_consumer(request)) # sets/returns global variable
contribs = client.contributions.get_entries(
project=project, _fields=["identifier", "id", "formula", "data"]
).result()[
"data"
] # first 20 only
data = []
for contrib in contribs:
data.append({})
for k, v in nested_to_record(contrib, sep=".").items():
if v is not None and not k.endswith(".value") and not k.endswith(".unit"):
vs = v.split(" ")
if k.endswith(".display") and len(vs) > 1:
key = k.replace("data.", "").replace(".display", "") + f" [{vs[1]}]"
data[-1][key] = vs[0]
else:
data[-1][k] = v
df = DataFrame(data)
response = HttpResponse(df.to_csv(), content_type="text/csv")
response["Content-Disposition"] = "attachment; filename={}.csv".format(project)
return response
示例14: download
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponse [as 別名]
def download(request, project):
cname = os.environ["PORTAL_CNAME"]
s3obj = f"{S3_DOWNLOAD_URL}{cname}/{project}.json.gz"
return redirect(s3obj)
# TODO check if exists, generate if not, progressbar...
# return HttpResponse(status=404)
示例15: rest_submission
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponse [as 別名]
def rest_submission(request):
if request.method == "POST":
serializer = QMCDBSetSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response([serializer.errors], status=status.HTTP_400_BAD_REQUEST)
return HttpResponse(status=400)