Django教程
- Django POST请求接口例子
- django配置mysql数据库-pymysql
- 关于media,static文件的动态使用和静态使用
- Django获取带参数url的参数值
- django配置404页面教程
- django模板常用的内置过滤器
- Jinja2配置自定义过滤器
- Django教程-定时任务crontab
- 解决uwsgi报错:No such process [core/uwsgi.c line 1693]
- 解决-doesn't declare an explicit app_label and isn't in an application in INSTALL
- Django教程-Model字段大全,选项详解
- Django教程-子应用添加后台管理
- Django教程-安装DjangoUeditor3
- Django教程-设置默认导包路径
- Django教程-Django配置redis
- Django教程-django配置mysql数据库
- Django教程-uwsgi配置详解
- Django model 字段类型大全
- Django ORM详解
- 解决:Django定时器无法启动
- Django教程-Django中配置jinja2模板
- Django教程-创建一个最简单的django项目
Django POST请求接口例子
有时候我们需要提供一个接口,接口的请求是post,本文为大家介绍post请求接口例子。
首页,我们需要设置请求接口路由,如下代码:
from django.conf.urls import url from . import views urlpatterns = [ url(r'^xray_api/$', views.scan_api.as_view()), ]
然后我们设置路由视图scan_api:如下代码:
class scan_api(View): def get(self,request): res_dict = {'error_msg':'Forbidden','error_code':'403','time':time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()+8*3600))} return JsonResponse(res_dict) def post(self,request): post_data = request.POST data_dict = {} linux_time = time.time()+8*3600 data_dict['post_time'] = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(linux_time)) txt_time = time.strftime('%Y%m%d_%H_%M_%S',time.localtime(linux_time)) try: token = base64.b64decode(post_data['token']).decode() dataValue = post_data['dataValue'] if token == 'abc': try: with open('/www/wwwroot/test/html/scan_api/' + txt_time + '.txt', 'w', encoding='utf-8') as f: f.write(dataValue) data_dict['success'] = 1 except Exception as e: print(e) data_dict['error_msg'] = 'Server error' data_dict['success'] = 0 else: data_dict['success'] = 0 data_dict['error_msg'] = 'Token error' except: data_dict['success'] = 0 data_dict['error_msg'] = 'key error' return JsonResponse(data_dict)
这样一个post请求接口就写好了,我们可以写一个提交测试代码,如下:
import requests import base64 url = 'https://www.test.com/xray_api/' data = "https://www.baidu.com,http://www.alibaba.com/,http://123.456.33.11,https://3.36.12.23:443" data_dict = {} data_dict['dataValue'] = data token = base64.b64encode('abc'.encode()) data_dict['token'] = token response = requests.post(url,data=data_dict).json() print(response) # 返回结果是:{'post_time': '2021-07-21 21:07:53', 'success': 1}
测试,没问题,ok就这样,一个完整的django post请求接口就写好了。
最后修改:2021-07-21 21:32:14