python-flask(一)

python web

web後端:與數據庫進行交互以處理相應的業務邏輯。需要考慮的是如何實現功能、數據的存取、平臺的穩定性與性能等
Web框架:用於進行Web開發的一套軟件架構
前端框架:vue,jquery,bootstrap
python後端框架三種:Python Web框架大致分成三類,分別是Full-Stack Web框架、Non Full-Stack Web框架、Asynchronous 異步框架。
flask:Non Full-Stack Web框架代表,是一個輕量級的Web Framework 小巧、靈活,它的很多功能需要開發者以插件的形式向裏安裝,你也可以自己定製
django:Full-Stack Web框架的代表,功能非常全面和成熟,開發文檔很完備。
tornado: Non Full-Stack Web框架 I/O性能吞吐高併發

創建環境

搭建框架:
1.要有虛擬環境:
linux: virtualenv virtualenvwrapper
配置文件的修改: .Envs
.bashrc

windows:pip install virtualenvwrapper-win
mkvirutalenv mytest1 (新建虛擬環境)
workon 查看已創建的虛擬環境(想切換的話,在後面跟上環境名)
deactivate 退出虛擬環境
rmvirutalenv 虛擬環境名

新建虛擬環境:
默認放在:C:\用戶\lenovo\Envs (路徑最好不要出現中文)
想修改的話:修改環境變量,在系統變量中新建 變量名:WORKON_HOME 變量值:自己定(如:C:\Envs)
新建:mkvirtualenv flaskenv
(flaskenv) C:\Users\running\Desktop\GPDay41\代碼\day41_flask>
說明進入到虛擬環境中…
安裝flask:
pip install flask
pip list (查看已安裝的庫)
打開pycharm-settings-Project Interptrter 將環境改爲我們剛創建的虛擬環境

flask框架搭建:

static:靜態文件夾 裏面存放網頁圖片
template:模板文件夾 存放所有HTML網頁
創建app.py:
from flask import Flask
ctrl+點擊Flask可以查看源碼:Flask是一個對象
WSGI:WSGI協議 只有python有 服務器就一個 框架有多個 遵循WSGI進行部署 web服務器調用WSGI協議調用應用程序框架的。
靜態資源:例如HTML文件,圖片文件,css,js文件
動態頁面:例如登錄頁面,查詢頁面,註冊頁面等與用戶交互的
在這裏插入圖片描述

app=  Flask(__name__) #__name__當前文件名字
app相當於一箇中心,其他東西圍繞它運轉

1.關聯服務器並啓動
app.run(host=‘0.0.0.0’,port=5000) #host默認127.0.0.0本機可以訪問 0.0.0.0任何可以訪問 端口號默認5000
在終端: python app.py 運行
瀏覽器裏訪問:127.0.0.0:5000 沒有東西 因爲沒有定義路由,沒有東西供你訪問
2. @app.route(’/’) 註冊路由
def func():
return …

@app.route('/')
def hello_world():
  return 'HELLO hello world'

現在可以在瀏覽器訪問了 127.0.0.0:5000實際上會127.0.0.0:5000/自動加上/表示根路由
在這裏插入圖片描述

配置:
Environment: production
production ----》 正在生產中
development —》開發
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.

  • Debug mode: off

run(deubg=True) ---->debug mode:on
on的模式: 代碼有改變則服務器自動重啓(重新加載程序)不需要我們手動調試

解耦:
settings.py:
ENV = ‘development’
DEBUG = True
在app啓動前引入文件(兩種):
1. app.config.from_object(settings)
2. app.config.from_pyfile(‘settings.py’)

二部分:
路由和請求request,響應response
flask是基於Werkzeug工具包的一個web服務框架,所以flask裏視圖函數的實現,實際上是對werkzeug的一層封裝

路由結合視圖函數
@app.route(’/’)
def hello_world(): # ---->視圖函數
return ‘HELLO hello world!hello kitty!’

@app.route('/abc',endpoint='abc1')
def show_abc():
    return '<h1>abc</h1>'

    # route就是將函數與add_url_rule進行了裝飾
    def show_name():
        return '千鋒教育'


    app.add_url_rule('/name', view_func=show_name)

路徑(路由)的變量規則:
轉換器:
str 默認
int 整型
float 浮點型
path 類似str,但是可以識別’/’
uuid 識別uuid類型的字符串

@app.route(’/news/int:num’) ---->int:num表示的就是一個變量
在這裏插入圖片描述

products = [{'name': 'huawei p30', 'price': '5999', 'color': '黑色'},
            {'name': 'mi mate30', 'price': '3999', 'color': '紅色'}, {
                'name': 'iphone 11', 'price': '10999', 'color': '黑色'}]
                
@app.route('/product/<name>')
def get_product(name):
    for product in products:
        value = product.get('name')
        if name in value:
            return product
            
@app.route('/product/<int:page>')
def show_product(page):
    print(type(page))  # <class 'int'>
    return '當前請求的是第' + str(page) + '頁數據!'

@app.route('/product/<float:price>')  # http://127.0.0.1:5000/product/2.9
def show_product2(price):  # price=2.9
    print(type(price))  # <class 'int'>
    return '當前商品的價格是:' + str(price)

@app.route('/product/<path:pp>')
def show_path(pp):
    print(type(pp))
    return '得到的是:' + pp
#http://127.0.0.1/product/aa/bb/cc 得到的是aa/bb/cc

import uuid
@app.route('/product')
def show_uuid():
	uid=uuid.uuid4() #用戶唯一標識
	print(type(uid))
	return '==>'+str(uid)

進行路由匹配的時候,會根據路由代碼的先後順序進行匹配,uuid應該寫在str之前,否則會被str匹配
@app.route(‘rule’,endpoint=‘value’)
定義路由時,最後面可以不加’/’,然後輸入網址時加上’/‘就進不去,保持URL的唯一性,而如果定義時加上’’,輸入網址時加不加’/’,都能進去,因爲不加’'網站會自動加上。

URL構建:
@app.route(‘rule’,endpoint=‘value’)
def func():
pass

url_for(‘endpoint’) -----------> 根據endpoint找到路由rule
endpoint不寫,默認是函數名:hello_world
在這裏插入圖片描述
請求:request
from flask import request
client 發出的請求

request對象 只要有請求則會產生一個request對象

@app.route('/')
def hello_world():
    print(request)  # <Request 'http://127.0.0.1:5000/?name=admin' [GET]>
@app.route('/login', methods=['GET', 'POST'])
def user_login():
    print(request.remote_addr)
    if request.remote_addr in black_list:
        return '哈哈哈你什麼都看不到啦'
    # request.method 獲取請求的方式
    if request.method == 'GET':
        print(request.args.get('a'))  # ?a=100&b=99    request.args 字典對象  request.args.get('a')  ---->100
        return render_template('register.html')
    else:
        # 獲取提交的數據
        # print(request.form)
        # print(request.values)
        username = request.form.get('username')
        password = request.form.get('password')
        # result = request.get_json()
        # result = request.get_data()
        # print(result)
        return 'username:' + username + ',password:' + password
        # return 'POST!'

request.method 獲取請求的方式
request.args.get(‘key’,默認值) ----> get
request.form.get(‘key’,默認值) ----> post
request.values ----> [dictA,dictB] dictA—GET dictB–POST
request.get_json() application/json 類型數據 ajax請求
request.get_data() 將數據構成一個字節字符串

request.remote_addr 獲取遠程的ip地址
print(request.path) # /
print(request.full_path) # /?name=admin
print(request.url) # http://127.0.0.1:5000/?name=admin
print(request.base_url) # http://127.0.0.1:5000/
print(request.url_root)
print(request.method) # ‘GET’
print(request.query_string) # b’name=admin’

響應對象:
response對象

@app.route('/login')
def user_login():
	return render_template('login.html')

@app.route('/abc')
def show_abc():
    s = '''
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
           h1{
             color:red;
           }
        </style>
    </head>
    <body>
        <h1>ABC</h1>
    </body>
    </html>
    '''
    # response = make_response(s)
    # response.headers['name']='mytest'
    # return response
    return s

templates或者app=Flask(name,template_folder=‘template’)
在視圖函數的返回值後面可以跟:
1.string 系統會自動將str轉成一個response對象
2.make_reponse( ) 構建response對象,可以給response對象添加一些頭部信息
3.jsonify(datas) 將datas轉成json的格式 dict默認使用此函數
4.render_template()
5.redirect()

@app.route('/news')
def show_news():
    if not news:
        return render_template('404.html')
        # return redirect('/notfound')

@app.route('/notfound')
def not_found():
    return render_template('404.html')
#redirect過程

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章