python—接口编写部分

最近准备整理一下之前学过的前端+小程序知识笔记,形成合集。顺便准备学一学接口部分,希望自己能成为一个全栈嘿嘿。建议关注收藏,持续更新技术文档。

前端知识技能树

http请求

GET和POST是HTTP请求的两种基本方法,

GETPOST
GET把参数包含在URL中POST通过request body传递参数
GET在浏览器回退时是无害的POST会再次提交请求
GET请求会被浏览器主动cachePOST不会,除非手动设置
GET产生的URL地址可以被BookmarkPOST不可以
GET请求只能进行url编码POST支持多种编码方式
GET比POST更不安全,因为参数直接暴露在URL上,所以不能用来传递敏感信息。
GET请求参数会被完整保留在浏览器历史记录里POST中的参数不会被保留。
GET请求在URL中传送的参数是有长度限制的没有
对参数的数据类型,GET只接受ASCII字符没有限制
GET产生一个TCP数据;对于GET方式的请求,浏览器会把http header和data一并发送出去,服务器响应200(返回数据);POST产生两个TCP数据包;对于POST,浏览器先发送header,服务器响应100 continue,浏览器再发送data,服务器响应200 ok(返回数据)。

HTTP有GET, POST, PUT, DELETE等等,HTTP的底层是TCP/IP。所以GET和POST的底层也是TCP/IP

(大多数)浏览器通常都会限制url长度在2K个字节,而(大多数)服务器最多处理64K大小的url,超过的部分,恕不处理。

因为POST需要两步,时间上消耗的要多一点,看起来GET比POST更有效。但是:

  1. GET与POST都有自己的语义,不能随便混用。
  2. 据研究,在网络环境好的情况下,发一次包的时间和发两次包的时间差别基本可以无视。而在网络环境差的情况下,两次包的TCP在验证数据包完整性上,有非常大的优点。
  3. 并不是所有浏览器都会在POST中发送两次包,Firefox就只发送一次。

浏览器缓存

后端知识技能树

python_api:flask+flask_restful

在开始之前呢,我们需要安装几个模块,flask+flask_restful

get接口

# coding=utf-8
import sys
import importlib
importlib.reload(sys)
from flask import *
import flask_restful

app = Flask(__name__)
api = flask_restful.Api(app)


class HelloWorld(flask_restful.Resource):
    def get(self):
        x=request.args['x']#获取参数中的值
          y=request.args['y']
        return {'hello':y,'donghu':x}#接口返回值

api.add_resource(HelloWorld, '/login',methods=['GET'])#页面路径


if __name__ == '__main__':
    app.run(host='0.0.0.0',port=80)#请求地址,以及端口

get接口编写完成,运行,然后在浏览器中输入http://127.0.0.1/login
能正常返回值,那就说明没有问题了。

post接口

# coding=utf-8
import sys
import importlib
importlib.reload(sys)
from flask import *
import flask_restful

app = Flask(__name__)
api = flask_restful.Api(app)

class HelloWorld(flask_restful.Resource):
    def post(self):
        x = request.form['x']#获取参数
        y=request.form['y']
        return {'hello':y,'donghu':x}

api.add_resource(HelloWorld, '/login2',methods=['POST'])

if __name__ == '__main__':
    app.run(host='0.0.0.0',port=80)

post接口和get接口编写方式上差不多,只是接收参数的方式稍有调整。运行,然后在浏览器中输入,http://127.0.0.1/login2,看是否能正常访问。

python_api:FastAPI+Tornado

python提供了很多web框架,帮助我们快速构建API,如Flask、FastAPI、Tornado。
Flask、FastAPI如出一辙,所以这里只讲FastAPI+Tornado,如何构建GET和POST接口。

pip install fastapi
pip install uvicorn
pip install tornado

# -*- coding: utf-8 -*-
from fastapi import FastAPI
from pydantic import BaseModel 
import uvicorn
 
app = FastAPI()
class Item(BaseModel):
    a: int = None
    b: int = None
 
@app.get('/test/a={a}/b={b}')
def calculate(a: int=None, b: int=None):
    c = a + b
    res = {"res":c}
    return res

@app.post('/test')
def calculate(request_data: Item):
    a = request_data.a
    b = request_data.b
    c = a + b
    res = {"res":c}
    return res 
 
if __name__ == '__main__':
    uvicorn.run(app=app,
                host="localhost",
                port=8000,
                workers=1)

将上述代码保存为get.py,存储在某一路径
首先,进入python文件路径,在控制台启动服务
浏览器测试:访问http://localhost:8000/test/a=31/b=12
在这里插入图片描述

postman测试:
在这里插入图片描述
FastAPI的交互测试:访问http://localhost:8000/docs
在这里插入图片描述
Tornado比FastAPI更能承受高并发。

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado import gen
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor
import time
from tornado.options import define, options
from tornado.platform.asyncio import to_asyncio_future,AsyncIOMainLoop
from tornado.httpclient import AsyncHTTPClient
import asyncio

define("port", default=8000, help="just run", type=int)

class MainHandler(tornado.web.RequestHandler):
    def main(self,a,b):
        c = float(a) + float(b)
        res = {"res":c}
        return res
    
    # get接口     
    def get(self):
        a = self.get_body_argument('a')
        b = self.get_body_argument('b')
        res = self.main(a,b) # 主程序计算
        self.write(json.dumps(res,ensure_ascii=False))
    
    # post接口   
    def post(self):
        a = self.get_body_argument('a')
        b = self.get_body_argument('b')
        res = int(a) * int(b) #主程序计算
        self.write(json.dumps(res,ensure_ascii=False))
         
if __name__ == "__main__":
    #运行程序
    application = tornado.web.Application([(r"/test", MainHandler),])
    application.listen(8000,'localhost')
    tornado.ioloop.IOLoop.instance().start()

在这里插入图片描述

  • 17
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值