docker setup

This commit is contained in:
AdrienLSH
2023-11-23 16:43:30 +01:00
parent fd19180e1d
commit f29003c66a
5410 changed files with 869440 additions and 0 deletions

View File

@ -0,0 +1,12 @@
from .urls import urlpatterns
from .decorators import api, param
from .client import API
from .exceptions import APIError
from .views import vue
from .log import log, error
urls = urlpatterns, 'restapi', 'api'
default_app_config = 'restapi.apps.RestapiConfig'

View File

@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

View File

@ -0,0 +1,6 @@
all_apis = []

View File

@ -0,0 +1,10 @@
from django.apps import AppConfig
from django.utils.module_loading import autodiscover_modules
class RestapiConfig(AppConfig):
name = 'restapi'
def ready(self):
autodiscover_modules('api')

View File

@ -0,0 +1,35 @@
import requests
from .exceptions import APIError
class API:
def __init__(self, server='127.0.0.1:8000'):
self.server = server
def __getattr__(self, name):
api_url = 'http://%s/api/%s/?json=true' % (self.server, name)
def call(*args, **kwargs):
api_args = requests.get(api_url).json()['args']
params = { _['name']: _['default'] for _ in api_args}
for i in range(len(args)):
params[api_args[i]['name']] = args[i]
params.update(kwargs)
res = requests.post(api_url, json=params)
result = res.json()
if 200 <= res.status_code < 400:
return result['result']
if 400 <= res.status_code < 500:
raise APIError(res.status_code, result['msg'], result['code'])
raise result
return call

View File

@ -0,0 +1,101 @@
from django.http import JsonResponse, HttpResponse
from django.urls import path
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
from .urls import urlpatterns
from .apis import all_apis
from .exceptions import APIError
from .log import log, error
import inspect
import json
import traceback
def param(name, type=str, comment=''):
def wrapper(func):
if not hasattr(func, '__params__'):
func.__params__ = {}
func.__params__[name] = { 'type': type, 'comment': comment }
return func
return wrapper
def api(func):
all_apis.append(func)
arg_spec = inspect.getargspec(func)
func.__args__ = args = [{
'name': _,
'required': True,
'default': None,
'type': 'str',
'comment': '',
} for _ in arg_spec.args]
if not hasattr(func, '__params__'):
func.__params__ = {}
default_count = len(arg_spec.defaults) if arg_spec.defaults else 0
for i in range(default_count):
arg = args[len(args) - default_count + i]
arg['required'] = False
arg['default'] = arg_spec.defaults[i]
@csrf_exempt
def django_view(request):
if request.method != 'POST':
args_doc = func.__args__[:]
for arg_doc in args_doc:
arg_name = arg_doc['name']
if arg_name in func.__params__:
arg_doc['type'] = func.__params__[arg_name]['type'].__name__
arg_doc['comment'] = func.__params__[arg_name]['comment']
is_json = request.GET.get('json', None)
ctx = { 'name': func.__name__, 'doc': func.__doc__, 'args': args_doc }
if is_json:
return JsonResponse(ctx)
else:
return render(request, 'restapi/api.html', ctx)
try:
params = json.loads(request.body.decode('utf-8'))
except:
return HttpResponse('参数无法解析', status=400)
# try:
result = func(**params)
success = True
log('[%s] called success' % func.__name__)
# except APIError as ex:
# result = {
# 'success': False,
# 'code': ex.code,
# 'msg': ex.msg
# }
# error('[%s] called with exception' % func.__name__)
# error('exception: %s' % str(ex))
# return JsonResponse(result, status=ex.status)
# except Exception as ex:
# result = {
# 'success': False,
# 'type': type(ex).__name__,
# 'exception': str(ex),
# 'stack': [(_.filename, _.lineno, _.line) for _ in traceback.extract_stack()]
# }
# error('[%s] called with internal error' % func.__name__)
# error('exception: %s' % str(ex))
# return JsonResponse(result, status=500)
return JsonResponse({ 'success': success, 'result': result })
urlpatterns.append(path('%s/' % func.__name__, django_view))
return func

View File

@ -0,0 +1,10 @@
class APIError(Exception):
def __init__(self, status=400, msg='', code=0):
self.status = status
self.msg = msg
self.code = code

View File

@ -0,0 +1,14 @@
import logging
logger = logging.getLogger('api')
def log(text, *args):
log_text = text if not args else text % tuple(args)
logger.info(log_text)
def error(text, *args):
log_text = text if not args else text % tuple(args)
logger.error(log_text)

View File

@ -0,0 +1,16 @@
from django.core.management import BaseCommand
from django.conf import settings
from restapi.client import API
import code
class Command(BaseCommand):
def handle(self, **options):
local_objects = {
'api': API(settings.API_SERVER if hasattr(settings, 'API_SERVER') else '127.0.0.1:8000'),
}
code.interact(local=local_objects)

View File

@ -0,0 +1,3 @@
from django.db import models
# Create your models here.

View File

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

View File

@ -0,0 +1,8 @@
from django.urls import path
from . import views
urlpatterns = [
path('', views.doc),
]

View File

@ -0,0 +1,18 @@
from django.shortcuts import render
from django.http import HttpResponse
from django.conf import settings
import os
def doc(request):
ctx = {}
return render(request, 'restapi/doc.html', ctx)
def vue():
def vue_view(request):
return render(request, 'index.html')
return vue_view