def handle_request(request):
return HttpResponse("Hello, World")
def register(request):
result = None
# check for post only
if request.method != 'POST':
result = {"error": "this method only accepts posts!"}
else:
try:
user = User.objects.create_user(request.POST['username'],
request.POST['email'],
request.POST['password'])
# optional fields
for field in ['first_name', 'last_name']:
if field in request.POST:
setattr(user, field, request.POST[field])
user.save()
result = {"success": True}
except KeyError as e:
result = {"error": str(e) }
response = HttpResponse(json.dumps(result))
if "error" in result:
response.status_code = 500
return response
# a decorator receives the method it's wrapping as a variable 'f'
def increment(f):
# we use arbitrary args and keywords to
# ensure we grab all the input arguments.
def wrapped_f(*args, **kw):
# note we call f against the variables passed into the wrapper,
# and cast the result to an int and increment .
return int(f(*args, **kw)) + 1
return wrapped_f # the wrapped function gets returned.
@increment def plus(a, b): return a + b result = plus(4, 6) assert(result == 11, "We wrote our decorator wrong!")
def post_only(f):
""" Ensures a method is post only """
def wrapped_f(request):
if request.method != "POST":
response = HttpResponse(json.dumps(
{"error": "this method only accepts posts!"}))
response.status_code = 500
return response
return f(request)
return wrapped_f
@post_only
def register(request):
result = None
try:
user = User.objects.create_user(request.POST['username'],
request.POST['email'],
request.POST['password'])
# optional fields
for field in ['first_name', 'last_name']:
if field in request.POST:
setattr(user, field, request.POST[field])
user.save()
result = {"success": True}
except KeyError as e:
result = {"error": str(e) }
response = HttpResponse(json.dumps(result))
if "error" in result:
response.status_code = 500
return response
def json_response(f):
""" Return the response as json, and return a 500 error code if an error exists """
def wrapped(*args, **kwargs):
result = f(*args, **kwargs)
response = HttpResponse(json.dumps(result))
if type(result) == dict and 'error' in result:
response.status_code = 500
return response
post_only
@json_response
def register(request):
try:
user = User.objects.create_user(request.POST['username'],
request.POST['email'],
request.POST['password'])
# optional fields
for field in ['first_name', 'last_name']:
if field in request.POST:
setattr(user, field, request.POST[field])
user.save()
return {"success": True}
except KeyError as e:
return {"error": str(e) }
@post_only
@json_response
def login(request):
if request.user is not None:
return {"error": "User is already authenticated!"}
user = auth.authenticate(request.POST['username'], request.POST['password'])
if user is not None:
if not user.is_active:
return {"error": "User is inactive"}
auth.login(request, user)
return {"success": True, "id": user.pk}
else:
return {"error": "User does not exist with those credentials"}
def parameterize_request(types=("POST",)):
"""
Parameterize the request instead of parsing the request directly.
Only the types specified will be added to the query parameters.
e.g. convert a=test&b=cv in request.POST to
f(a=test, b=cv)
"""
def wrapper(f):
def wrapped(request):
kw = {}
if "GET" in types:
for k, v in request.GET.items():
kw[k] = v
if "POST" in types:
for k, v in request.POST.items():
kw[k] = v
return f(request, **kw)
return wrapped
return wrapper
@post_only
@json_response
@parameterize_request(["POST"])
def register(request, username, email, password,
first_name=None, last_name=None):
user = User.objects.create_user(username, email, password)
user.first_name=first_name
user.last_name=last_name
user.save()
return {"success": True}
def increment(f):
""" Increment a function result """
wrapped_f(a, b):
return f(a, b) + 1
return wrapped_f
@increment
def plus(a, b)
""" Add two things together """
return a + b
plus.__name__ # this is now 'wrapped_f' instead of 'plus'
plus.__doc__ # this now returns 'Increment a function result' instead of 'Add two things together'
from functools import wraps
def increment(f):
""" Increment a function result """
@wraps(f)
wrapped_f(a, b):
return f(a, b) + 1
return wrapped_f
@increment
def plus(a, b)
""" Add two things together """
return a + b
plus.__name__ # this returns 'plus'
plus.__doc__ # this returns 'Add two things together'
$ sudo easy_install decorator
$ pip install decorator
from decorator import decorator
@decorator
def post_only(f, request):
""" Ensures a method is post only """
if request.method != "POST":
response = HttpResponse(json.dumps(
{"error": "this method only accepts posts!"}))
response.status_code = 500
return response
return f(request)
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有