python接口怎么写-Python教程

资源魔 21 0

1、flask

flask是一个python编写的轻量级框架,能够应用它完成一个网站或许web效劳。本文就用flask来开发一个接口。

flask需求先装置再援用。pip install flask

用flask开发接口的流程为:

一、界说一个server

server=flask.Flask(__name__) #__name__代表以后的python文件。把以后的python文件当作一个效劳启动

二、而后界说接口函数,普通函数以及接口函数的区分正在于,界说为接口的函数上方要特地加之:

@server.route('/index',methods=['get','post']) #第一个参数就是门路,第二个参数支持的申请形式,没有写的话默许是get
 
@server.route('/index',methods=['get','post'])#第一个参数就是门路,第二个参数支持的申请形式,没有写的话默许是get
def index():
    res={'msg':'这是我开发的第一个捏词','msg_code':0}
    return json.dumps(res,ensure_ascii=False)

三、让server执行起来

server.run(port=7777,debug=True,host='0.0.0.0')
#port可自界说填写。没有要与机械上已占用的port抵触。
#debug=True,正在代码进行修正后,顺序会主动从新加载,不必再次运转。也就是运转一次便可,即便改动代码,也没有需求重启效劳
#host内陆ip地点,写0.0.0.0,能够让其余人间接拜访本机的ip。
#终极这个接口的拜访地点就是  http://127.0.0.1/index  ,get办法或许post办法均可。前往数据是json格局res内容

示例:

import flask,json
server=flask.Flask(__name__)#__name__代表以后的python文件。把以后的python文件当作一个效劳启动
@server.route('/index',methods=['get','post'])#第一个参数就是门路,第二个参数支持的申请形式,没有写的话默许是get
def index():
    res={'msg':'这是我开发的第一个捏词','msg_code':0}
    return json.dumps(res,ensure_ascii=False)
server.run(port=7777,debug=True,host='0.0.0.0')

接口拜访中,常常会需求输出参数。那末假如要承受传入的参数,则可用如下办法:

  username=flask.request.values.get('username')

示例:

import flask,json
server=flask.Flask(__name__)#__name__代表以后的python文件。把以后的python文件当作一个效劳启动
@server.route('/reg',methods=['post'])#只有正在函数前加之@server.route (),这个函数才是个接口,没有是普通的函数
def reg():
    username=flask.request.values.get('username')
    passwd=flask.request.values.get('passwd')
    if username and passwd:
        sql='select * from my_user where username="%s";'%username
        print(sql)
        if my_db(sql):
            res={'msg':'用户已存正在','msg_code':2001}
        else:
            insert_sql='insert into my_user (username,passwd,is_admin) values ("%s","%s",0);'%(username,passwd)
            my_db(insert_sql)
            res={'msg':'注册胜利','msg_code':0}
    else:
        res={'msg':'必填字段未填,请查看接口文档','msg_code':1001} #1001示意必填接口未填
    return json.dumps(res,ensure_ascii=False)
server.run(port=7777,debug=True,host='0.0.0.0')
#端口没有写默许是5000.debug=True示意改了代码后不必重启,会主动帮你重启.host写0.0.0.0,他人就能够经过ip拜访接口。不然就是127.0.0.1

2、cookie操作解决

假定正在做登录接口的时分,要增加cookie到内陆,则需求对接口前往的json串做一下操作:

res = flask.make_response(json_res) #json_res是接口前往数据。而后对json_res正在做操作,结构成前往后果的工具
res.set_cookie(key,session_id,3600) #最初的数字是cookie的生效工夫。这样设置当前,正在执行登录接口胜利登录,则会同时正在内陆退出cookie。此中key以及session_id的值依据实际状况界说

例子:

@server.route('/login',methods=['get'])
def login():
    username = flask.request.values.get('username')
    pwd = flask.request.values.get('pwd')
    if username == 'zy' and pwd=='123456':
        session_id = tools.my_md5(username+time.strftime('%Y%m%d%H%M%S'))
        key = 'txz_session:%s'%username
        tools.op_redis(key,session_id,600)
        res = {'session_id':session_id,'error_code':0,'msg':'登录胜利',
               'login_time':time.strftime('%Y%m%d%H%M%S') } #给用户前往的信息
        json_res = json.dumps(res,ensure_ascii=False)#前往后果弄成json
        res = flask.make_response(json_res)  #结构成前往后果的工具
        res.set_cookie(key,session_id,3600) #最初的数字是cookie的生效工夫。
        return res

以上操作可胜利保留cookie到内陆。当前接口中需求应用coookie的时分,只要猎取:

cookies = flask.request.cookies #一切的cokies,是个字典。而后可经过字典猎取到对应的cookie,并执行操作。

例:比方正在做一些操作的时分,必需正在登录状态下才能够,这时候候就能够间接拿内陆登录时的cookie中内容以及效劳器中的内容进行比对,假如有分歧的,阐明已胜利登录

@server.route('/posts')
def posts():
    cookies = flask.request.cookies  #一切的cokies
    username = ''  #
    session = ''#界说这两个变量是为了,正在不传cookie的时分用的。
    for key,value in cookies.items():
        if key.startswith('txz_session'): #判别cookie以txz_session扫尾的话,取到它
            username = key
            session = value  #挪用接口的时分用户传过的seesion,从cookie外面取过去的
    redis_session = tools.op_redis(username) #从redis外面猎取到的的cookie
    if redis_session == session:  #判别传过去的seeion以及redis外面的session同样
        title = f

相干保举:《Python教程》

以上就是python接口怎样写的具体内容,更多请存眷资源魔其它相干文章!

标签: python教程 python编程 python使用问题 python接口

抱歉,评论功能暂时关闭!