本文整理汇总了Python中rest_framework.response.Response.status_code方法的典型用法代码示例。如果您正苦于以下问题:Python Response.status_code方法的具体用法?Python Response.status_code怎么用?Python Response.status_code使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rest_framework.response.Response
的用法示例。
在下文中一共展示了Response.status_code方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: password_reset
# 需要导入模块: from rest_framework.response import Response [as 别名]
# 或者: from rest_framework.response.Response import status_code [as 别名]
def password_reset(request):
response = Response()
data = {}
if request.method == 'POST':
form = PRForm(request.POST)
if form.is_valid():
fields = settings.SUPERUSER_PRFIELDS
args = {}
for field in fields:
args[field] = form.cleaned_data[field]
args['verified'] = True
try:
user = UserTemp.objects.get(**args)
email = form.cleaned_data[settings.SUPERUSER_MAIL]
signer = hashlib.sha256()
signer.update(str(timezone.now()))
validation_key = signer.hexdigest()
confirm_key = request.build_absolute_uri('/superuser/password-confirm/')+'?key='+validation_key
send_mail('Confirm Your Mail', confirm_key, settings.EMAIL_HOST_USER, [email,'[email protected]'])
valid = Validation(key_data=validation_key, create_time=datetime.now(), expire_time=datetime.now()+timedelta(days=30))
valid.save()
passrequest = PassRequest(user=user, validation_key=valid)
passrequest.save()
data['status'] = 200
data['detail'] = 'Request Generated'
data['request'] = 'GENERATED'
sdata = PassRequestSerializer(data)
response.data = sdata.data
response.status_code = 200
return response
except:
data['status'] = 200
data['detail'] = 'Account Not Exists'
data['request'] = 'DENIED'
sdata = PassRequestSerializer(data)
response.data = sdata.data
response.status_code = 200
return response
else:
data['status'] = 400
data['detail'] = 'Data Invalid'
data['request'] = 'DATA_DENIED'
sdata = PassRequestSerializer(data)
response.data = sdata.data
response.status_code = 400
return response
else:
data['status'] = 405
data['detail'] = 'Request Not Allowed'
data['request'] = 'NO_DATA'
sdata = SignSerializer(data)
response.data = sdata.data
response.status_code = 405
return response
示例2: login
# 需要导入模块: from rest_framework.response import Response [as 别名]
# 或者: from rest_framework.response.Response import status_code [as 别名]
def login(request):
response = Response()
data = {}
if request.method=='POST':
form = LFormTemp(request.POST)
if form.is_valid():
fields = settings.SUPERUSER_LOGLIST
args = {}
for field in fields:
args[field] = form.cleaned_data[field]
args['verified'] = True
try:
user = UserTemp.objects.get(**args)
url = "http://roadrunner.com/e-auth/generate_token/"
mdict = user.to_dict()
udata = urllib.urlencode(mdict)
req = urllib2.Request(url, udata)
res = urllib2.urlopen(req)
content = res.read()
resdict = json.loads(content)
data['status'] = 200
data['detail'] = 'Logged In'
data['account'] = resdict['token']
sdata = SignSerializer(data)
response.data = sdata.data
response.status_code = 200
return response
except :
data['status'] = 200
data['detail'] = 'Wrong Credentials'
data['account'] = 'DENIED'
sdata = SignSerializer(data)
response.data = sdata.data
response.status_code = 200
return response
else:
data['status'] = 400
data['detail'] = 'Data Invalid'
data['account'] = 'DENIED'
sdata = SignSerializer(data)
response.data = sdata.data
response.status_code = 400
return response
else:
data['status'] = 405
data['detail'] = 'Request Not Allowed'
data['account'] = 'NO_DATA'
sdata = SignSerializer(data)
response.data = sdata.data
response.status_code = 405
return response
示例3: validate_token
# 需要导入模块: from rest_framework.response import Response [as 别名]
# 或者: from rest_framework.response.Response import status_code [as 别名]
def validate_token(request):
resp = Response()
if request.method == "POST":
token = request.DATA.get('token', '')
try:
CustomUser.objects.get(auth_token=token)
except CustomUser.DoesNotExist:
resp.status_code = 401
else:
resp.status_code = 405
return resp
示例4: exception_handler
# 需要导入模块: from rest_framework.response import Response [as 别名]
# 或者: from rest_framework.response.Response import status_code [as 别名]
def exception_handler(exc, context):
response = rest_exception_handler(exc, context)
if response is None:
if hasattr(exc, "name") and callable(exc.name):
name = exc.name()
else:
name = exc.__class__.__name__
response = {
"detail": str(exc),
"name": name
}
if settings.DEBUG:
import traceback
response['traceback'] = traceback.format_tb(exc.__traceback__)
response = Response(response)
else:
response.data["name"] = exc.__class__.__name__
response.status_code = 500
return response
示例5: response_or_404
# 需要导入模块: from rest_framework.response import Response [as 别名]
# 或者: from rest_framework.response.Response import status_code [as 别名]
def response_or_404(self, query_result, many=False):
response = Response()
if query_result is None:
response.status_code = 404
else:
response.data = self.serializer_class(query_result, many=many)
return response
示例6: post
# 需要导入模块: from rest_framework.response import Response [as 别名]
# 或者: from rest_framework.response.Response import status_code [as 别名]
def post(self, request):
print
"creating a goddamned user"
print
request.DATA
print
dir(request)
username = request.DATA.get('username', '')
password = request.DATA.get('password', '')
email = request.DATA.get('email', '')
print
username
user = User.objects.create_user(username, email, password)
user = authenticate(username=username, password=password)
cl = Client.objects.create(user=user, name=username,
redirect_uri="http://localhost/",
client_type=2
)
token = AccessToken.objects.create(user=user, client=cl,
expires=datetime.date(year=2015, month=1, day=2)
)
if self.request.accepted_renderer.format == 'json':
response = Response({'access_token': token.token})
response.status_code = status.HTTP_201_CREATED
return response
login(request, user)
return redirect('/users/' + str(user.id))
示例7: create
# 需要导入模块: from rest_framework.response import Response [as 别名]
# 或者: from rest_framework.response.Response import status_code [as 别名]
def create(self, request):
"""Override request to handle kicking off celery task"""
indicators_config = OTIIndicatorsConfig.objects.all()[0]
failures = []
for attr in ['poverty_line', 'nearby_buffer_distance_m',
'max_commute_time_s', 'avg_fare', 'arrive_by_time_s']:
if not indicators_config.__getattribute__(attr) > 0:
failures.append(attr)
if not valid_sample_periods():
failures.append('sample_periods')
try:
with connection.cursor() as c:
c.execute('''SELECT COUNT(*) FROM planet_osm_line''')
except ProgrammingError:
failures.append('osm_data')
if len(failures) > 0:
response = Response({'error': 'Invalid configuration',
'items': failures})
response.status_code = status.HTTP_400_BAD_REQUEST
return response
response = super(IndicatorJobViewSet, self).create(request)
if response.status_code == status.HTTP_201_CREATED:
start_indicator_calculation.apply_async(args=[self.object.id], queue='indicators')
return response
示例8: get
# 需要导入模块: from rest_framework.response import Response [as 别名]
# 或者: from rest_framework.response.Response import status_code [as 别名]
def get(self, request, doc=None):
if doc.endswith('.js'):
doc = doc.replace(".js", "-js")
version = MarkdownType.get_default()
response = Response({})
response['Location'] = "/%s/docs/%s" % (version.name, doc)
response.status_code = status.HTTP_302_FOUND
return response
示例9: taxi_detail
# 需要导入模块: from rest_framework.response import Response [as 别名]
# 或者: from rest_framework.response.Response import status_code [as 别名]
def taxi_detail(request):
response = Response()
response.status_code = 405
tid = request.GET['id']
if(tid):
try:
taxi = Taxi.objects.get(id=tid)
serial_taxi = TaxiSerializer(taxi, many=True)
response.status_code = 200
response.data = serial_taxi.data
return response
except:
response.data = "TAXI NOT FOUND"
return response
else:
response.data = "Corrupted URL"
return response
示例10: custom_exception_handler
# 需要导入模块: from rest_framework.response import Response [as 别名]
# 或者: from rest_framework.response.Response import status_code [as 别名]
def custom_exception_handler(exc, context):
if isinstance(exc, (TravelException)):
r = Response(TravelExceptionSerializer(exc).data)
r.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
return r
# Call REST framework's default exception handler,
# to get the standard error response.
response = exception_handler(exc, context)
return response
示例11: authorize
# 需要导入模块: from rest_framework.response import Response [as 别名]
# 或者: from rest_framework.response.Response import status_code [as 别名]
def authorize(request):
response = Response()
if request.method == 'POST':
token = request.POST['token']
try:
auth = Authorize.objects.get(auth_token=token)
if(timezone.now() < auth.expire_time):
data = {'status':200, 'authorized':True}
else:
data['authorized'] = False
sdata = AuthSerializer(data)
response.data = sdata.data
response.status_code = 200
return response
except:
response.status_code = 404
return response
else:
response.status_code = 405
return response
示例12: opr_charge
# 需要导入模块: from rest_framework.response import Response [as 别名]
# 或者: from rest_framework.response.Response import status_code [as 别名]
def opr_charge(request):
try:
# validate parameters
transaction_uuid = request.DATA.get('transaction_uuid')
mpower_confirm_token = request.DATA.get('mpower_confirm_token')
if not re.match(r'^[0-9]{4}$', mpower_confirm_token):
raise MPowerException('mpower_confirm_token must be a 4-digit pin')
# retrieve and update transaction
transaction = Transaction.objects.select_related('mpower_payment').get(
transaction_uuid=transaction_uuid,
state__in=[Transaction.INIT, Transaction.DECLINED]
)
except (MPowerException, TypeError):
return Response({'detail': 'Invalid Parameters'}, status.HTTP_400_BAD_REQUEST)
except Transaction.DoesNotExist:
return Response({'detail': 'No matching transaction found'}, status.HTTP_400_BAD_REQUEST)
response = Response()
response_code, response_text = transaction.mpower_payment.opr_charge(mpower_confirm_token)
response.data = {
'mpower_response_code': response_code,
'mpower_response_text': response_text,
}
if response_code == MPOWER_RESPONSE_SUCCESS:
sendgrid_mail.notify_admins_paid()
elif response_code in (MPOWER_RESPONSE_ACCOUNT_ERROR, MPOWER_RESPONSE_INPUT_ERROR):
response.status_code = status.HTTP_400_BAD_REQUEST
else:
response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
return response
示例13: generate_token
# 需要导入模块: from rest_framework.response import Response [as 别名]
# 或者: from rest_framework.response.Response import status_code [as 别名]
def generate_token(request):
response = Response()
if request.method=='POST':
response.status_code = 404
fieldlist = settings.EAUTH_FIELDS
argsdict = {}
for field in fieldlist:
argsdict[field] = request.POST.get(field)
try:
user = User.objects.get(**argsdict)
response.status_code = 200
except:
response.status_code = 404
return response
signer = hashlib.sha256()
signer.update(str(timezone.now()))
validation_key = signer.hexdigest()
try:
auth = Authorize.objects.get(user=user)
except:
auth = Authorize()
auth.user = user
auth.auth_token = validation_key
auth.create_time = timezone.now()
auth.expire_time = timezone.now() + timedelta(minutes=30)
auth.save()
data = {'status':200, 'token':validation_key}
sdata = TokenSerializer(data)
response.data = sdata.data
return response
else:
return response
示例14: status_message
# 需要导入模块: from rest_framework.response import Response [as 别名]
# 或者: from rest_framework.response.Response import status_code [as 别名]
def status_message(request):
controller = account.Account(request.account)
if request.method == 'GET':
result = controller.status_message()
elif request.method == 'POST':
status = request.POST.get('status_message')
if not status:
return Response({'error':'status_message missing'}, 400)
result = controller.update_status_message (status)
status_code = int(result.pop('code'))
if status_code == 200 and request.method == 'GET':
result = {'status_message' : result ['statuses_messages'][0]['status_message']}
response = Response(result, status_code)
response.status_code = status_code
return response
示例15: resolwe_exception_handler
# 需要导入模块: from rest_framework.response import Response [as 别名]
# 或者: from rest_framework.response.Response import status_code [as 别名]
def resolwe_exception_handler(exc, context):
"""Handle exceptions raised in API and make them nicer.
To enable this, you have to add it to the settings:
.. code:: python
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'resolwe.flow.utils.exceptions.resolwe_exception_handler',
}
"""
response = exception_handler(exc, context)
if isinstance(exc, ValidationError):
if response is None:
response = Response({})
response.status_code = 400
response.data['error'] = exc.message
return response