最近研究了一下python的django框架, 发现这个框架不比Java spring boot差, mock同样一个接口, 代码量少很多, 维护起来也很方便, 废话不多说,直接上代码
1. 安装django: pip install django
2. 创建项目: django-admin startproject postdemo
3. 启动项目: python manage.py runserver 0.0.0.0:8001
启动Django项目就这么简单, 三步完成, O(∩_∩)O
postdemo 包下创建views.py
from django.http import HttpResponse from .utils import process_parameters, validate_parameters, read_response def postdemo(request):
if request.method == 'POST':
dic_params = process_parameters(request.body.decode('utf-8')) # 一定要用utf-8解码,不然传入的是bytes类型b'body'
if validate_parameters(dic_params):
result = read_response()
res = HttpResponse(result)
# res.__setitem__("resultcode", '0') # 用这个也OK, __setitem__可以修改默认的header, 比如Content-Type, setdefault不行
res.setdefault('resultcode', '')
res.setdefault('msg', 'no error')
return res
else:
return HttpResponse('error username or password!')
else:
return HttpResponse('error method!')
postdemo 包下创建utils.py, 定义业务逻辑方法, 采用函数式编程也可以
import configparser
import json def read_config():
config = configparser.ConfigParser()
dic = {}
config.read("./config.ini", encoding="utf8")
config.sections()
dic["username"] = config.get("login", "username")
dic["password"] = config.get("login", "password")
return dic def read_response():
config = configparser.ConfigParser()
dic = {}
config.read("./config.ini", encoding="utf8")
config.sections()
dic["nickname"] = config.get("response_data", "nickname")
dic["sex"] = config.get("response_data", "sex")
dic["age"] = config.get("response_data", "age")
dic["status"] = config.getint("response_data", "status")
dic["uid"] = config.get("response_data", "uid")
return json.dumps(dic, ensure_ascii=False) def process_parameters(body):
try:
body_dic = {}
key_values = str(body).split("&")
for key_value in key_values:
body_dic[key_value.split("=")[0]] = key_value.split("=")[1]
return body_dic
except Exception as e:
return e def validate_parameters(body):
if isinstance(body, dict):
dic_config = read_config()
if dic_config["username"] == body["username"] and dic_config["password"] == body["password"]:
return True
else:
return False
postdemo包平级目录创建配置文件config.ini
[login]
username=123456789@qq.com
password=123456 [response_data]
nickname=旦增尼玛
sex=1
age=18
status=1
uid=123456789
默认文件urls.py, 添加path
from django.contrib import admin
from django.urls import path from . import views urlpatterns = [
path('admin/', admin.site.urls),
path('postdemo', views.postdemo),
]
默认文件setting.py, 注释掉中间件的csrf安全验证, 其他默认
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
到这里就完了, 一个简单的post 接口就完成了, 如果还有进行cookie等校验, 完善utils.py业务处理逻辑即可, 启动项目