本文整理汇总了Python中rest_framework.response.Response方法的典型用法代码示例。如果您正苦于以下问题:Python response.Response方法的具体用法?Python response.Response怎么用?Python response.Response使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rest_framework.response
的用法示例。
在下文中一共展示了response.Response方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get
# 需要导入模块: from rest_framework import response [as 别名]
# 或者: from rest_framework.response import Response [as 别名]
def get(self, request, id, format=None):
strategy_id = id
if strategy_id:
strategy_obj = Strategy.objects.get(id=strategy_id)
code_text = strategy_obj.source_code.code_text
backtest.delay(
strategy_id=strategy_id,
code_text=code_text,
class_name="DoubleMaStrategy",
vt_symbol="IF88.CFFEX",
interval="1m",
start_date=datetime(2016, 1, 1),
end_date=datetime(2019, 1, 1),
rate=3.0 / 10000,
slippage=0.2,
size=300,
pricetick=0.2,
capital=1_000_000,
)
return Response({"status": "Process"})
return Response({"status": "Error"})
示例2: get_delete_update_puppy
# 需要导入模块: from rest_framework import response [as 别名]
# 或者: from rest_framework.response import Response [as 别名]
def get_delete_update_puppy(request, pk):
try:
puppy = Puppy.objects.get(pk=pk)
except Puppy.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
# get details of a single puppy
if request.method == 'GET':
serializer = PuppySerializer(puppy)
return Response(serializer.data)
# update details of a single puppy
if request.method == 'PUT':
serializer = PuppySerializer(puppy, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_204_NO_CONTENT)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# delete a single puppy
if request.method == 'DELETE':
puppy.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
示例3: get_post_puppies
# 需要导入模块: from rest_framework import response [as 别名]
# 或者: from rest_framework.response import Response [as 别名]
def get_post_puppies(request):
# get all puppies
if request.method == 'GET':
puppies = Puppy.objects.all()
serializer = PuppySerializer(puppies, many=True)
return Response(serializer.data)
# insert a new record for a puppy
if request.method == 'POST':
data = {
'name': request.data.get('name'),
'age': int(request.data.get('age')),
'breed': request.data.get('breed'),
'color': request.data.get('color')
}
serializer = PuppySerializer(data=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)
示例4: warranty
# 需要导入模块: from rest_framework import response [as 别名]
# 或者: from rest_framework.response import Response [as 别名]
def warranty(request):
from servo.api.serializers import DeviceSerializer
sn = request.GET.get('sn')
if not sn:
return error('Need query parameter for warranty lookup')
try:
GsxAccount.default(request.user)
except Exception as e:
return error('Cannot connect to GSX (check username and password)')
try:
result = Device.from_gsx(sn, cached=False)
serializer = DeviceSerializer(result, context={'request': request})
return Response(serializer.data)
except Exception as e:
return error(e)
示例5: custom_exception_handler
# 需要导入模块: from rest_framework import response [as 别名]
# 或者: from rest_framework.response import Response [as 别名]
def custom_exception_handler(exc, context):
# give more context on the error since DRF masks it as Not Found
if isinstance(exc, Http404):
set_rollback()
return Response(str(exc), status=status.HTTP_404_NOT_FOUND)
# Call REST framework's default exception handler after specific 404 handling,
# to get the standard error response.
response = exception_handler(exc, context)
# No response means DRF couldn't handle it
# Output a generic 500 in a JSON format
if response is None:
logging.exception('Uncaught Exception', exc_info=exc)
set_rollback()
return Response({'detail': 'Server Error'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
# log a few different types of exception instead of using APIException
if isinstance(exc, (DeisException, ServiceUnavailable, HealthcheckException)):
logging.exception(exc.__cause__, exc_info=exc)
return response
示例6: destroy
# 需要导入模块: from rest_framework import response [as 别名]
# 或者: from rest_framework.response import Response [as 别名]
def destroy(self, request, **kwargs):
calling_obj = self.get_object()
target_obj = calling_obj
if request.data.get('username'):
# if you "accidentally" target yourself, that should be fine
if calling_obj.username == request.data['username'] or calling_obj.is_superuser:
target_obj = get_object_or_404(User, username=request.data['username'])
else:
raise PermissionDenied()
# A user can not be removed without apps changing ownership first
if len(models.App.objects.filter(owner=target_obj)) > 0:
msg = '{} still has applications assigned. Delete or transfer ownership'.format(str(target_obj)) # noqa
raise AlreadyExists(msg)
try:
target_obj.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
except ProtectedError as e:
raise AlreadyExists(e)
示例7: passwd
# 需要导入模块: from rest_framework import response [as 别名]
# 或者: from rest_framework.response import Response [as 别名]
def passwd(self, request, **kwargs):
if not request.data.get('new_password'):
raise DeisException("new_password is a required field")
caller_obj = self.get_object()
target_obj = self.get_object()
if request.data.get('username'):
# if you "accidentally" target yourself, that should be fine
if caller_obj.username == request.data['username'] or caller_obj.is_superuser:
target_obj = get_object_or_404(User, username=request.data['username'])
else:
raise PermissionDenied()
if not caller_obj.is_superuser:
if not request.data.get('password'):
raise DeisException("password is a required field")
if not target_obj.check_password(request.data['password']):
raise AuthenticationFailed('Current password does not match')
target_obj.set_password(request.data['new_password'])
target_obj.save()
return Response({'status': 'password set'})
示例8: regenerate
# 需要导入模块: from rest_framework import response [as 别名]
# 或者: from rest_framework.response import Response [as 别名]
def regenerate(self, request, **kwargs):
obj = self.get_object()
if 'all' in request.data:
for user in User.objects.all():
if not user.is_anonymous:
token = Token.objects.get(user=user)
token.delete()
Token.objects.create(user=user)
return Response("")
if 'username' in request.data:
obj = get_object_or_404(User,
username=request.data['username'])
self.check_object_permissions(self.request, obj)
token = Token.objects.get(user=obj)
token.delete()
token = Token.objects.create(user=obj)
return Response({'token': token.key})
示例9: update
# 需要导入模块: from rest_framework import response [as 别名]
# 或者: from rest_framework.response import Response [as 别名]
def update(self, request, **kwargs):
app = self.get_object()
old_owner = app.owner
if request.data.get('owner'):
if self.request.user != app.owner and not self.request.user.is_superuser:
raise PermissionDenied()
new_owner = get_object_or_404(User, username=request.data['owner'])
app.owner = new_owner
# ensure all downstream objects that are owned by this user and are part of this app
# is also updated
for downstream_model in [models.AppSettings, models.Build, models.Config,
models.Domain, models.Release, models.TLS]:
downstream_model.objects.filter(owner=old_owner, app=app).update(owner=new_owner)
app.save()
return Response(status=status.HTTP_200_OK)
示例10: app
# 需要导入模块: from rest_framework import response [as 别名]
# 或者: from rest_framework.response import Response [as 别名]
def app(self, request, *args, **kwargs):
app = get_object_or_404(models.App, id=kwargs['id'])
perm_name = "api.use_app"
usernames = [u.id for u in get_users_with_perms(app)
if u.has_perm(perm_name, app)]
data = {}
result = models.Key.objects \
.filter(owner__in=usernames) \
.values('owner__username', 'public', 'fingerprint') \
.order_by('created')
for info in result:
user = info['owner__username']
if user not in data:
data[user] = []
data[user].append({
'key': info['public'],
'fingerprint': info['fingerprint']
})
return Response(data, status=status.HTTP_200_OK)
示例11: users
# 需要导入模块: from rest_framework import response [as 别名]
# 或者: from rest_framework.response import Response [as 别名]
def users(self, request, *args, **kwargs):
app = get_object_or_404(models.App, id=kwargs['id'])
request.user = get_object_or_404(User, username=kwargs['username'])
# check the user is authorized for this app
if not permissions.is_app_user(request, app):
raise PermissionDenied()
data = {request.user.username: []}
keys = models.Key.objects \
.filter(owner__username=kwargs['username']) \
.values('public', 'fingerprint') \
.order_by('created')
if not keys:
raise NotFound("No Keys match the given query.")
for info in keys:
data[request.user.username].append({
'key': info['public'],
'fingerprint': info['fingerprint']
})
return Response(data, status=status.HTTP_200_OK)
示例12: decorator_view
# 需要导入模块: from rest_framework import response [as 别名]
# 或者: from rest_framework.response import Response [as 别名]
def decorator_view(request):
"""
tags:
- test
parameters:
- in: formData
name: id
description: Person ID
type: integer
required: true
methods:
- post
responses:
200:
description: Status [200, 400, 403, 405]
schema:
type: object
properties:
status:
type: integer
enum: [200, 400, 403, 405]
"""
return Response(dict())
示例13: update
# 需要导入模块: from rest_framework import response [as 别名]
# 或者: from rest_framework.response import Response [as 别名]
def update(self, request, *args, **kwargs):
"""
---
responses:
201:
description: 'Redefined response method'
schema:
allOf:
- $ref: '#/definitions/TestModelSeriazlizer'
- type: 'object'
properties:
new_custom_field2:
type: string
200:
description: 'Redefined response method'
schema:
allOf:
- $ref: '#/definitions/TestModelSeriazlizer'
- type: 'object'
properties:
new_custom_field3:
type: string
"""
return Response(dict())
示例14: list
# 需要导入模块: from rest_framework import response [as 别名]
# 或者: from rest_framework.response import Response [as 别名]
def list(self, request):
"""
Returns site metrics data for current month
TODO: NEXT Add query params to get data from previous months
TODO: Add paginagation
"""
site = django.contrib.sites.shortcuts.get_current_site(self.request)
course_keys = figures.sites.get_course_keys_for_site(site)
date_for = datetime.utcnow().date()
month_for = '{}/{}'.format(date_for.month, date_for.year)
data = []
for course_key in course_keys:
data.append(metrics.get_month_course_metrics(site=site,
course_id=str(course_key),
month_for=month_for))
return Response(data)
示例15: new_users
# 需要导入模块: from rest_framework import response [as 别名]
# 或者: from rest_framework.response import Response [as 别名]
def new_users(self, request):
"""
TODO: Rename the metrics module function to "new_users" to match this
"""
site = django.contrib.sites.shortcuts.get_current_site(self.request)
date_for = datetime.utcnow().date()
months_back = 6
new_users = metrics.get_monthly_history_metric(
func=metrics.get_total_site_users_joined_for_time_period,
site=site,
date_for=date_for,
months_back=months_back,
)
data = dict(new_users=new_users)
return Response(data)