|
1 | | -importinspect |
2 | 1 | importjson |
3 | 2 | importlogging |
| 3 | +importtraceback |
4 | 4 | fromdatetimeimportdatetime |
5 | 5 | fromioimportStringIO |
6 | 6 | frompathlibimportPath |
|
15 | 15 | fromdjango.contrib.auth.mixinsimportLoginRequiredMixin |
16 | 16 | fromdjango.contrib.messages.viewsimportSuccessMessageMixin |
17 | 17 | fromdjango.formsimportModelForm |
18 | | -fromdjango.httpimportJsonResponse,HttpResponseBadRequest,HttpResponse |
| 18 | +fromdjango.httpimportJsonResponse,HttpResponse |
19 | 19 | fromdjango.viewsimportView |
20 | 20 | fromdjango.views.genericimportCreateView |
21 | 21 | fromdjango_user_agents.utilsimportget_user_agent |
|
34 | 34 |
|
35 | 35 |
|
36 | 36 | defapi_view(request,method_name): |
37 | | -body=request.body |
38 | 37 | try: |
39 | 38 | method=getattr(API(request),method_name) |
40 | | -exceptAttributeError: |
41 | | -log.error('Unknown method %s, body = %s',method_name,body) |
42 | | -returnHttpResponseBadRequest() |
43 | | -try: |
| 39 | +body=request.body |
44 | 40 | body=body.decode('utf8') |
45 | | -exceptUnicodeDecodeError: |
46 | | -log.exception('Failed to decode %s',body) |
47 | | -returnHttpResponseBadRequest() |
48 | | -log.info('API request: method = %s, body = %s',method_name,body) |
49 | | -try: |
50 | 41 | args=json.loads(body) |
51 | | -exceptValueErrorase: |
52 | | -log.error('JSON decode error: %s',e) |
53 | | -returnHttpResponseBadRequest() |
54 | | -signature=inspect.signature(method) |
55 | | -try: |
56 | | -signature.bind(**args) |
57 | | -exceptTypeErrorase: |
58 | | -log.error(e) |
59 | | -returnHttpResponseBadRequest() |
60 | | -forarg_name,hintinget_type_hints(method).items(): |
61 | | -ifarg_name=='return': |
62 | | -continue |
63 | | -arg=args[arg_name] |
64 | | -ifnotisinstance(arg,hint): |
65 | | -log.warning( |
66 | | -'Incorrect type for argument %s = %r of method %s: found %s, expected %s', |
67 | | -arg_name,arg,method_name,arg.__class__.__name__,hint.__name__) |
68 | | -result=method(**args) |
69 | | -ifnotisinstance(result,dict): |
70 | | -result= {'result':result} |
71 | | -returnJsonResponse(result,json_dumps_params=dict(indent=4,sort_keys=True)) |
| 42 | +forarg_name,hintinget_type_hints(method).items(): |
| 43 | +ifarg_name=='return': |
| 44 | +continue |
| 45 | +arg=args[arg_name] |
| 46 | +ifnotisinstance(arg,hint): |
| 47 | +log.warning( |
| 48 | +'Incorrect type for argument %s = %r of method %s: found %s, expected %s', |
| 49 | +arg_name,arg,method_name,arg.__class__.__name__,hint.__name__) |
| 50 | +result=method(**args) |
| 51 | +ifnotisinstance(result,dict): |
| 52 | +result= {'result':result} |
| 53 | +exceptException: |
| 54 | +result=dict( |
| 55 | +error=dict( |
| 56 | +traceback="".join(traceback.format_exc()), |
| 57 | + ) |
| 58 | + ) |
| 59 | +returnJsonResponse(result) |
72 | 60 |
|
73 | 61 |
|
74 | 62 | classAPI: |
|