本文整理汇总了Python中django.http.response.HttpResponse.status_code方法的典型用法代码示例。如果您正苦于以下问题:Python HttpResponse.status_code方法的具体用法?Python HttpResponse.status_code怎么用?Python HttpResponse.status_code使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.http.response.HttpResponse
的用法示例。
在下文中一共展示了HttpResponse.status_code方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: employes
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import status_code [as 别名]
def employes(request):
msg = check_access(request)
if msg == 'ok':
if 'page' in request.GET:
page = paginate(request.GET['page'], Employe.objects.all())
if page is None:
resp = HttpResponse()
resp.status_code = 500
return resp
objects = page.object_list
else:
objects = get_list_or_404(Employe)
employe_list = ["emp: {0} position: {1} id: {2}".format(obj.user.first_name,
obj.position.name,
obj.user.id) for obj in objects]
response_data = {}
response_data['items_cnt'] = len(employe_list)
response_data['employes'] = employe_list
resp = HttpResponse(json.dumps(response_data), content_type="application/json")
resp.status_code = 200
return resp
else:
resp = HttpResponse()
resp.status_code = 401
return resp
示例2: post
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import status_code [as 别名]
def post(self, request, *args, **kwargs):
payload = json.loads(request.body.decode('utf-8'))
if request.META.get('HTTP_X_GITHUB_EVENT') == "ping":
return HttpResponse('Hi!')
if False:
if request.META.get('HTTP_X_GITHUB_EVENT') != "push":
response = HttpResponse()
response.status_code = 403
return response
signature = request.META.get('HTTP_X_HUB_SIGNATURE').split('=')[1]
secret = settings.GITHUB_HOOK_SECRET
if isinstance(secret, str):
secret = secret.encode('utf-8')
mac = hmac.new(secret, msg=request.body, digestmod=sha1)
if not hmac.compare_digest(mac.hexdigest(), signature):
response = HttpResponse()
response.status_code = 403
return response
handle_push_hook_request(payload)
return HttpResponse("OK")
示例3: get_majors
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import status_code [as 别名]
def get_majors(request):
tour_id = request.GET.get('tour', None)
major1_id = request.GET.get('major1', None)
major2_id = request.GET.get('major2', None)
if tour_id and major1_id and major2_id:
try:
tour = Tour.objects.get(id=tour_id)
majors = tour.majors.filter().exclude(id__in=[major1_id, major2_id])
data = serializers.serialize("json", majors)
return HttpResponse(data, content_type='application/json')
except Tour.DoesNotExist:
response = HttpResponse(content_type='application/json')
response.status_code = 400
return response
else:
if tour_id and major1_id:
try:
tour = Tour.objects.get(id=tour_id)
majors = tour.majors.all().exclude(id__in=[major1_id])
data = serializers.serialize("json", majors)
return HttpResponse(data, content_type='application/json')
except Tour.DoesNotExist:
response = HttpResponse(content_type='application/json')
response.status_code = 400
return response
else:
response = HttpResponse(content_type='application/json')
response.status_code = 400
return response
示例4: position_id
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import status_code [as 别名]
def position_id(request, pos_id):
msg = check_access(request)
if msg == 'ok':
access_code = request.META['HTTP_AUTHORIZATION']
acc_obj = access_token.objects.get(token=access_code)
user = acc_obj.user
str_user_id = "{0}".format(user.id)
str_pos_id = "{0}".format(pos_id)
if str_user_id != str_pos_id:
resp = HttpResponse()
resp.status_code = 403
return resp
try:
emp_obj = Employe.objects.get(user=pos_id)
except Employe.DoesNotExist:
raise Http404
position = emp_obj.position
response_data = {}
response_data['full_name'] = user.first_name
response_data['position_name'] = position.name
response_data['salary'] = position.salary
response_data['salary_currency'] = position.salary_currency
resp = HttpResponse(json.dumps(response_data), content_type="application/json")
resp.status_code = 200
return resp
else:
resp = HttpResponse()
resp.status_code = 401
return resp
示例5: employe_id
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import status_code [as 别名]
def employe_id(request, emp_id):
msg = check_access(request)
if msg == 'ok':
access_code = request.META['HTTP_AUTHORIZATION']
acc_obj = access_token.objects.get(token=access_code)
user = acc_obj.user
str_user_id = "{0}".format(user.id)
str_emp_id = "{0}".format(emp_id)
if str_user_id != str_emp_id:
resp = HttpResponse()
resp.status_code = 403
return resp
try:
emp_obj = Employe.objects.get(user=emp_id)
except Employe.DoesNotExist:
raise Http404
position = emp_obj.position
response_data = {}
response_data['full_name'] = user.first_name
response_data['username'] = user.username
response_data['email'] = user.email
response_data['mobile_phone'] = user.mobile_phone
response_data['birthday'] = user.birth_day
response_data['position'] = position.name
resp = HttpResponse(json.dumps(response_data), content_type="application/json")
resp.status_code = 200
return resp
else:
resp = HttpResponse()
resp.status_code = 401
return resp
示例6: register
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import status_code [as 别名]
def register(request):
'''View function handling user registration.
This function parse and validate incoming request's form data and check
table auth_user for authenticity before storing user record in table or
output error message.
Args:
request: Incoming request.
Returns:
Indicator that user is successfully created or error message that either
form data is invalid or user exists.
'''
form = UserForm(request.POST)
response = HttpResponse()
if form.is_valid():
try:
user = User.objects.create_user(form.cleaned_data['name'],
password=form.cleaned_data['passwd'])
success(request, 'Successfully create user.')
except IntegrityError:
error(request, 'User name exists.')
response.status_code = 400
else:
error(request, 'Invalid input data')
response.status_code = 400
response.write(''.join([item.message for item in get_messages(request)]))
return response
示例7: log_in
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import status_code [as 别名]
def log_in(request):
'''View function corresponding to url /login.
The purpose of this function vary with http method. If method is GET it
behaves as unauthorize redirect destination; If method is POST it accepts
request's form data, validates it and adds session to authorize the user.
Args:
request: Incoming request
Returns:
When GET, indicate the page has been redirected here; When POST,
return either message that user is logged in or error that form invalid
or user name/password error.
'''
response = HttpResponse()
if request.method == 'GET':
info(request, 'Indicator')
else:
form = UserForm(request.POST)
if form.is_valid():
user = authenticate(username=form.cleaned_data['name'],
password=form.cleaned_data['passwd'])
if user != None:
login(request, user)
success(request, 'User exists.')
else:
error(request, 'User does not exist.')
response.status_code = 400
else:
error(request, 'Invalid input data')
response.status_code = 400
response.write(''.join([item.message for item in get_messages(request)]))
return response
示例8: healthcheck
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import status_code [as 别名]
def healthcheck(request):
"""Simple view to display the result of defined
healthchecks
:param request: django request
:return: Django response containing text/plain
"""
# dictionary containing functions to be called
checks = {'DB': _test_db_connection,
'Topics': _test_topics_connection,
'Events search': _test_events_search}
response = HttpResponse()
overall_ok = True
for name, service in checks.iteritems():
try:
# run the healthcheck function
ok, message = service()
except Exception as e:
ok = False
message = e
logger.error('Error in healthcheck {name}'.format(name=name), exc_info=True)
if not ok:
overall_ok = False
response.write('* !! {service}: {text}\n'.format(service=name, text=message))
else:
response.write('* {service}: {text}\n'.format(service=name, text=message.replace('\n', '')))
response['Content-Type'] = "text/plain; charset=utf-8"
response['Cache-Control'] = "must-revalidate,no-cache,no-store"
if overall_ok:
response.status_code = 200
else:
response.status_code = 500
return response
示例9: is_logged
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import status_code [as 别名]
def is_logged(request):
if request.user.is_authenticated():
res = HttpResponse("")
res.status_code = 200
return res
else:
res = HttpResponse("Unauthorized")
res.status_code = 401
return res
示例10: postImageContent
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import status_code [as 别名]
def postImageContent(request):
userId = request.session.get(KEY_USER_ID, '')
if not userId:
return HttpResponse('你还未登录或登录已过期')
print(str(request.POST))
images = request.POST.getlist('images[]')
texts = request.POST.getlist('texts[]')
title = request.POST.get('title')
category = request.POST.get('category')
author = request.POST.get('author')
print("分类:", category)
articleType = 3 # 图文
contentType = 3 # 图文
if articleService.addImageArticle(userId, title, category, contentType, articleType, images, texts, author):
return HttpResponse(SUCCESS)
else:
response = HttpResponse(ERROR)
response.status_code = 500
return response
示例11: _http_auth_helper
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import status_code [as 别名]
def _http_auth_helper(self, request):
# At this point, the user is either not logged in, or must log
# in using http auth. If they have a header that indicates a
# login attempt, then use this to try to login.
if 'HTTP_AUTHORIZATION' in request.META:
auth = request.META['HTTP_AUTHORIZATION'].split()
if len(auth) == 2:
if auth[0].lower() == 'basic':
# Currently, only basic http auth is used.
uname, passwd = base64.b64decode(auth[1]).split(':')
user = authenticate(username=uname, password=passwd)
if user and user.is_staff:
request.session['moat_username'] = uname
return
# The username/password combo was incorrect, or not provided.
# Challenge the user for a username/password.
resp = HttpResponse()
resp.status_code = 401
try:
# If we have a realm in our settings, use this for the
# challenge.
realm = settings.HTTP_AUTH_REALM
except AttributeError:
realm = ""
resp['WWW-Authenticate'] = 'Basic realm="%s"' % realm
return resp
示例12: attach
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import status_code [as 别名]
def attach(request, app_name):
'''View function to attach facebook/twitter account to user.
If a twitter account is to be attached, the incoming request is simply an
indicator. This function then call twitter request_token api to ask for a
temporary twitter token and twitter secret token, save it to database and
send back to the client.
Args:
request: Incoming request.
app_name: The name of social network to be attached.
Returns:
Token string if twitter token is successfully received. Error message
if network is not supported.
'''
response = HttpResponse()
if app_name == 'facebook':
success(request, 'facebook account attached')
elif app_name == 'twitter':
request_token_url = 'https://api.twitter.com/oauth/request_token'
oauth = OAuth1(client_key,
client_secret=client_secret)
r = requests.post(url=request_token_url,
auth=oauth,
data={'oauth_callback': 'http://ec2-54-173-9-169.compute-1.amazonaws.com:9090/twitter'})
twitter_query = QueryDict(r.content)
UserProfile.insert_twitter_token(twitter_query, request.user)
return HttpResponse(twitter_query['oauth_token'])
else:
error(request, 'Unsupported social network')
response.status_code = 400
response.write(''.join([item.message for item in get_messages(request)]))
return response
示例13: process_request
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import status_code [as 别名]
def process_request(self, request):
"""
Parse the session id from the 'Session-Id: ' header when using the api.
"""
if self.is_api_request(request):
try:
parsed_session_uri = parse_session_id(request)
if parsed_session_uri is not None:
domain = get_domain(request)
if parsed_session_uri['realm'] != domain:
raise exceptions.PermissionDenied(
_('Can not accept cookie with realm %s on realm %s') % (
parsed_session_uri['realm'],
domain
)
)
session_id = session_id_from_parsed_session_uri(
parsed_session_uri)
request.session = start_or_resume(
session_id, session_type=parsed_session_uri['type'])
request.parsed_session_uri = parsed_session_uri
# since the session id is assigned by the CLIENT, there is
# no point in having csrf_protection. Session id's read
# from cookies, still need csrf!
request.csrf_processing_done = True
return None
except exceptions.APIException as e:
response = HttpResponse('{"reason": "%s"}' % e.detail,
content_type='application/json')
response.status_code = e.status_code
return response
return super(HeaderSessionMiddleware, self).process_request(request)
示例14: index
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import status_code [as 别名]
def index(request):
response_data = {}
response_data['server'] = 'oauth2_server.com'
response_data['version'] = 'django {0}'.format(get_version())
resp = HttpResponse(json.dumps(response_data), content_type="application/json")
resp.status_code = 200
return resp
示例15: make_response
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import status_code [as 别名]
def make_response(status=200, content=None):
if content is None:
content = {}
response = HttpResponse()
response.status_code = status
response['Content-Type'] = "application/json"
response.content = json.dumps(content)
return response