python學習筆記-day8-1-【python flask接口開發】


今天說說python使用flask如何進行接口開發。

一、安裝Python依賴庫

pip install flask

二、Flask使用

1、使用Flask開發接口,運行代碼與接口代碼同在一個文件里

 1 import flask
 2 import json
 3 
 4 
 5 # print(__name__) #__main__,代表當前Python文件
 6 server = flask.Flask(__name__) #起動一個服務,把咱們當前這個Python文件,當做一個服務
 7 
 8 #裝飾器
 9 #ip:8000/index?uge
10 @server.route('/index',methods=['get']) #默認是get請求,可以不寫或是同時寫get,post
11 def index():
12     res = {'msg':'這是我開發的第一個接口', 'msg_code': 0}
13     return json.dumps(res, ensure_ascii=False) #二進制轉化為utf-8
14 
15 @server.route('/reg', methods=['post'])
16 def reg():
17     username = flask.request.values.get('username')
18     pwd = flask.request.values.get('passwd')
19     if username and pwd:
20         sql = 'select * from my_user where username="%s";' %username
21         if my_db(sql):
22             res = {'msg':'用戶已存在', 'msg_code':2001}
23         else:
24             insert_sql = 'insert into my_user (username,passwd,is_admin)VALUES ("%s","%s",0);' %(username,pwd)
25             my_db(insert_sql)
26             res = {'msg':'注冊成功.', 'msg_code':0}
27     else:
28         res = {'msg':'必填字段未填,請查看接口文檔!', 'msg_code':1001}
29         #1001必填字段未填
30     return json.dumps(res, ensure_ascii=False)
31 
32 #debug=True,修改代碼后,不需要重啟服務,它會幫你自動重啟
33 server.run(port=7777, debug=True, host='0.0.0.0')  #起動服務。默認端口號是5000,
34 # host='0.0.0.0'指定后,別人可以通過ip訪問,監聽所有的網卡

 

運行方式:

在IDE里直接運行,get請求可以在瀏覽器直接請求,Post請求可以自己寫請求代碼,或使用Postman等工具都可以。

 

2、按不同的目錄組織代碼結構,實現更好模塊化管理

 

其中interface.py為接口實現邏輯:如readme描述:

這個是api接口
/reg
注冊接口
入參:
username:
passwd:
啟動程序是在bin目錄下

啟動程序
python bin/start.py

 

 新的interface.py

import flask,json
from lib.tools import my_db,op_redis,my_md5

#寫接口的邏輯
# print(__name__) #__main__,代表當前Python文件
server = flask.Flask(__name__) #起動一個服務,把咱們當前這個Python文件,當做一個服務


#裝飾器
#ip:8000/index?uge
@server.route('/index',methods=['get']) #默認是get請求,可以不寫或是同時寫get,post
def index():
    res = {'msg':'這是我開發的第一個接口', 'msg_code': 0}
    return json.dumps(res, ensure_ascii=False) #二進制轉化為utf-8

@server.route('/reg', methods=['post'])
def reg():
    username = flask.request.values.get('username')
    pwd = flask.request.values.get('passwd')
    if username and pwd:
        sql = 'select * from my_user where username="%s";' %username
        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,pwd)
            my_db(insert_sql)
            res = {'msg':'注冊成功.', 'msg_code':0}
    else:
        res = {'msg':'必填字段未填,請查看接口文檔!', 'msg_code':1001}
        #1001必填字段未填
    return json.dumps(res, ensure_ascii=False)

start.py:

from lib.interface import server
from config.setting import SERVER_PORT


#debug=True,修改代碼后,不需要重啟服務,它會幫你自動重啟
server.run(port=SERVER_PORT, debug=True, host='0.0.0.0')  #起動服務。默認端口號是5000,
# host='0.0.0.0'指定后,別人可以通過ip訪問,監聽所有的

 

 

 三、有關系的接口怎么來開發

這里主要說一下,如果下面的接口依賴前面的接口的,應該怎么使用呢?如一些接口依賴登錄后才能進行相關的操作,這個時候可以通過cookie來獲取相應的登錄信息

1、還是據二的目錄,interface.py如下

 

 

import flask,time,json
from lib import tools

server = flask.Flask(__name__)
@server.route('/login')
def login():
    username = flask.request.values.get('username')
    pwd = flask.request.values.get('pwd')
    if username == 'xxxxxx' and pwd == '123456':
        #登錄成功,寫session
        session_id = tools.my_md5(username+time.strftime(time.strftime('%Y%m%d%H%M%S')))
        key = 'txz_session:%s' %username
        tools.op_redis(key, session_id, 120)
        res = {'session_id': session_id,
               'error_code':0,
               'msg': '登錄成功',
               'login_time':time.strftime(time.strftime('%Y%m%d%H%M%S'))} #用戶的返回結果
        json_res = json.dumps(res, ensure_ascii=False)
        res = flask.make_response(json_res)  #make_response,構造成返回結果的對象
        cookie_key = 'txz_session:%s' %username
        res.set_cookie(cookie_key,session_id,3600) #600是cookie的失效時間
        return res



@server.route('/posts')
def posts():
    # print(flask.request.cookies) #打印cookie
    cookies = flask.request.cookies
    username = ''
    session = ''
    for key,value in cookies.items():
        if key.startswith('txz_session'): #判斷cookie以txz開頭的話,取到它
            username=key
            print(username)
            session= value #調用接口的時候用戶傳過來的session,從cookie里面取過來的
            print(value)
    #redis
    redis_session = tools.op_redis(username)
    if redis_session == session: #判斷傳過來的session,與redis里的session是否一樣
        title = flask.request.values.get('title')
        content = flask.request.values.get('content')
        article_key = 'article:%s' % title
        tools.op_redis(article_key,content)  # 把文章寫入redis
        res = {'msg': '文章發表成功!', 'code': 0}
    else:
        res = {'msg': '用戶未登錄', 'code': 2009}

    print('user...', username)
    print('session_id', session)

    # session = flask.request.values.get('')

    return json.dumps(res, ensure_ascii=False)


#http://127.0.0.1:8989/all_posts開發一個獲取所有文章的接口
@server.route('/all_posts')
def all_posts():
    # print(flask.request.cookies) #打印cookie
    cookies = flask.request.cookies
    username = ''
    session = ''
    for key,value in cookies.items():
        if key.startswith('txz_session'): #判斷cookie以txz開頭的話,取到它
            username=key
            session= value #調用接口的時候用戶傳過來的session,從cookie里面取過來的
    #redis
    redis_session = tools.op_redis(username)
    if redis_session == session: #判斷傳過來的session,與redis里的session是否一樣
        all_keys = tools.op_redis_keys('article*')
        # print(all_keys)
        all_article = {}
        #[b'article:Python\xe6\x8e\xa5\xe5\x8f\xa3\xe5\xbc\x80\xe5\x8f\x91', b'article:lily']
        for title in all_keys:
            print(title.decode('utf-8'))
            str_title = title.decode('utf-8')
            key_title = str_title.split(':')[-1]
            all_article[key_title] = tools.op_redis(title)

        res = {'articles': all_article, 'code': 0}
    else:
        res = {'msg': '用戶未登錄', 'code': 2009}

    return json.dumps(res, ensure_ascii=False)

 

start.py:

import sys,os
# sys.path.insert(0, r'D:\python_code\syz\syz-biji\day8\new_api')

# print(os.path.abspath(__file__)) #windows下的__file__分隔符問題
BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #獲取程序主目錄
sys.path.insert(0,BASE_PATH)

from lib.interface import server
from config.setting import SERVER_PORT

server.run(host='0.0.0.0', port=SERVER_PORT, debug=True)

 

 四、總結

1、使用Flask可以開發相應的接口,快速實現mock接口等操作。

2、有依賴的接口使用cookie進行相應的處理,先在客戶端setcookie后,在使用接口時進行獲取驗證。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM