【Python】Flask

運行Flask

執行manage.py文件

python manage.py runserver -h 0.0.0.0 -p 80
  • 在地址 0.0.0.0 端口號 80啓動服務器

python manage.py runserver 可選參數

optional arguments:
  -?, --help            show this help message and exit
  -h HOST, --host HOST
  -p PORT, --port PORT
  --threaded
  --processes PROCESSES
  --passthrough-errors
  -d, --debug           enable the Werkzeug debugger (DO NOT use in production
                        code)
  -D, --no-debug        disable the Werkzeug debugger
  -r, --reload          monitor Python files for changes (not 100% safe for
                        production use)
  -R, --no-reload       do not monitor Python files for changes
  --ssl-crt SSL_CRT     Path to ssl certificate
  --ssl-key SSL_KEY     Path to ssl key

路由層

路由規則

# views.py
from flask import Blueprint
blue = Blueprint('blue',__name__)

# 藍圖懶加載
def init_blue(app):
    app.register_blueprint(blue)

—不傳遞參數

# views.py
@blue.route('/index/')
def index():
    return "index"

—傳遞任意參數

# views.py
@blue.route('/get_param/<id>/')
def get_param(id):
	print("參數:%s 類型:%s"%(id,type(id)))
    return "get_param success!"

—傳遞int型參數

# views.py
@blue.route('/get_int/<int:id>/')
def get_int(id):
    print("參數:%s 類型:%s"%(id,type(id)))
    return "get_int success!"

—傳遞float型參數

# views.py
@blue.route('/get_float/<float:id>/')
def get_float(id):
    print("參數:%s 類型:%s"%(id,type(id)))
    return "get_float success!"

—傳遞string型參數

# views.py
@blue.route('/get_string/<string:token>/')
def get_string(token):
    print("參數:%s 類型:%s"%(token,type(token)))
    return "get_string success!"

—傳遞path型參數 以最後一個"/"結束

# views.py
@blue.route('/get_path/<path:path>/')
def get_path(path):
    print("參數:%s 類型:%s"%(path,type(path)))
    return "get_path success!"

—傳遞uuid型參數

# views.py
@blue.route('/get_uuid/<uuid:uuid>/')
# uuid:cfc37378-5420-69f0-bd7c-57933b317afb
def get_uuid(uuid):
    print("參數:%s 類型:%s"%(uuid,type(uuid)))
    return "get_uuid success!"

—傳遞可選參數

# views.py
@blue.route('/get_any/<any(a,b):any_one>/')
def get_any(any_one):
    print("參數:%s 類型:%s"%(any_one,type(any_one)))
    return "get_any success!"

多路由映射

# blue.py
@blue.route('/get_string/<string:token>/')
@blue.route('/get_token/<int:token>/')
def get_string(token):
    return "傳入的參數:%s 類型:%s"%(token,what_type(token))

路由請求類型

—默認請求類型

默認支持 GET,HEAD,OPTIONS 其餘請求不支持
支持其他請求(POST,PUT,DELETE,CONNECT,TRACE,PATCH)需手動註冊

—註冊其他請求類型

# blue.py
@blue.route('/get_token/<int:token>/',methods=['POST','DELETE','PATCH'])
def get_string(token):
    return "請求成功!"

視圖層

Flask內置四大對象

—內置四大對象

內置四大對象:
	request
	g
	session
	config

—引入實例對象

from flask import request,g,session,config

● request(請求相關)

類型      request對象屬性    說明
---------------------------------------------
str	     url               # url地址
str	     url_charset       # url編碼規則
str	     url_root          # url根路徑
str	     url_rule          # url規則

str      headers           # 請求頭
dict     args              # get請求的參數
dict     form              # 提交的表單數據
dict     cookies           # 客戶端cookies的值
dict     files             # 文件數據
str      remote_addr       # 遠程地址
str      remote_user       # 遠程用戶
str      referrer          # 參考鏈接
str      method            # 請求方法
str      host              # 主機      
str      host_url          # 主機url地址
str      base_url          # 基本url地址

str      charset           # 請求報文編碼
dict     environ           # 環境和報文信息
bytes    query_string      # 請求參數字節形式
str      path              # 視圖路徑
str      full_path         # 視圖帶參路徑
str      blueprint         # 藍圖名
list     trusted_hosts     # 可信任的主機列表
 
str      accept_mimetypes  # 資源媒體類型
dict     access_route      # 通過的路由
str      accept_languages  # 可接受的語言
str      accept_encodings  # 可接受的編碼
str      accept_charsets   # 可接受的字符編碼

bool	 is_multiprocess   # 是否是多進程
bool	 is_multithread    # 是否是多線程
bool	 is_json           # 是否是json數據
bool	 is_run_once       # 是否立即運行
bool	 is_secure         # 是否安全

content_type
content_md5
max_forwards
date
script_root
want_form_data_parsed
shallow
stream
scheme
routing_exception
pragma
parameter_storage_class
mimetype_params
max_form_memory_size
is_xhr
input_stream
if_unmodified_since
if_range
if_none_match
cache_control
authorization
if_match
values
range
url_charset
url
if_modified_since
content_length
dict_storage_class
max_content_length
endpoint
view_args
disable_data_descriptor
data
encoding_errors
json_module

● g(數據相關)

● session(會話相關)

● config(配置相關)

Request

args
	請求參數
	query_string
	query_params
	get請求參數
	所有請求都能獲取該參數
form
	表單數據
	post請求參數(直接支持put,patch)
	ImmutableMultiDict args和form都是該類型數據是dict的子類

Response

● 參數設置

@blue.route('路徑地址')
def response():
	return 文本內容,狀態碼

● 返回方式

1.直接返回字符串

# views.py
@blue.route('/test_response1/')
def test_response1():
    return '<h1>This is content</h1>',403

2.使用make_response()

# views.py
from flask import make_response
@blue.route('/test_response2/')
def test_response2():
    response=make_response('<h1>This is content</h1>')
    return response,200

3.構建Response對象

# views.py
from flask import Response
@blue.route('/test_response3/')
def test_response3():
    response=Response('<h1>This is content</h1>')
    return response,200

4.加載html模板返回

# views.py
from flask import render_template
@blue.route('/test_response4/')
def test_response4():
    response=render_template('index.html')
    return response,200

● 重定向

—引入重定向

from flask import redirect

—使用重定向

# views.py
from flask import redirect
@blue.route('/redirect/')
def redirect_to_index():
    return redirect('/')

● 反向解析

—引入重定向和反向解析

from flask import redirect,url_for

—反向解析格式

# blue = Blueprint('blue',__name__) Blueprint裏面的'blue'就是藍圖名
from flask import redirect,url_for
@blue.route('/redirect/')
def redirect_to_index():
    return redirect(url_for('藍圖名.函數名',參數名=))

—不傳參反向解析

# blue.py
from flask import redirect,url_for
@blue.route('/redirect/')
def redirect_to_index():
    return redirect(url_for('blue.index'))

—傳參數反向解析

# blue.py
from flask import redirect,url_for
@blue.route('/redirect/')
def redirect_to_index():
    return redirect(url_for('blue.get_any',an='a'))

● 終止處理

—引入終止處理

from flask import abort

—構造403終止處理

from flask import abort
@blue.route('/test_abort/')
def test_abort():
    abort(403)
    return '403 is setted ok!'

—修改錯誤碼提示

# exceptions.py
class Forbidden(HTTPException):
    """*403* `Forbidden`

    Raise if the user doesn't have the permission for the requested resource
    but was authenticated.
    """

    code = 403 # 錯誤碼
    description = (
        "You don't have the permission to access the requested"
        " resource. It is either read-protected or not readable by the"
        " server." # 錯誤碼描述內容
    )

● 異常捕獲

@blue.errorhandler(403)
def feedback(error): # error爲必選自定義參數,缺少則會報錯
    return 'this is a 403'

會話技術

● cookie

—設置客戶端cookie中的鍵值

@blue.route('/login/',methods=['GET','POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    elif request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        response = Response("登錄成功%s"%username)
        response.set_cookie('username',username)
        response.set_cookie('password',password)
        return response

在這裏插入圖片描述
—獲取客戶端cookie中的鍵值

@blue.route('/mine')
def profile():
    username = request.cookies.get('username')
    response = Response("歡迎回來%s"%username)
    return response

在這裏插入圖片描述

● session

—設置session中的鍵值

@blue.route('/login/',methods=['GET','POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    elif request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        session['username'] = username
        session['password'] = password
        response = Response("登錄成功%s"%username)
        return response
    else:
        return 'ERROR!'

在這裏插入圖片描述
—獲取session中的鍵值

@blue.route('/mine/')
def profile():
    username = session.get('username')
    response = Response("歡迎回來%s"%username)
    return response

在這裏插入圖片描述
—session持久化
安裝模塊
官方文檔 https://pythonhosted.org/Flask-Session/

pip install flask-session

配置flask-session

# settings.py
class Config:
    DEBUG = False
    TESTING = False
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    SECRET_KEY = 'abc'                     # 設置session的安全祕鑰

    SESSION_TYPE = 'redis'                 # 設置session的儲存方式
    SESSION_COOKIE_NAME = 'session'        # 設置session名
    SESSION_REDIS = redis.Redis(host="127.0.0.1",port=6379) # 設置redis服務器地址端口

加載插件

from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_session import Session
db = SQLAlchemy()
migrate = Migrate()


def init_extension(app):
    db.init_app(app)
    migrate.init_app(app,db)
    # 加載session插件
    Session(app)

flask-session中可選用的配置參數

# settings.py 中 Config類可配置選項
    SESSION_TYPE = 'redis'                 # 設置session的儲存方式
    SESSION_PERMANENT = True               # 設置session是否爲永久
    SESSION_USE_SIGNER = False             # 設置session簽名
    SESSION_KEY_PREFIX = 'session:'        # 設置session的key的前綴
    SESSION_REDIS = redis.Redis(host="127.0.0.1", port=6379)  # 設置redis服務器地址端口
    SESSION_MEMCACHED = memcache.Client()  # 設置memcache服務器地址端口
    SESSION_FILE_DIR = '/'                 # 設置session的文件路徑
    SESSION_FILE_THRESHOLD =500            # 設置session最大的會話數
    SESSION_FILE_MODE = 'o6oo'             # 設置文件的模式
    SESSION_MONGODB = pymongo.MongoClient(host='127.0.0.1',host=27017)# 設置Mongo服務器地址端口
    SESSION_MONGODB_DB = 'flask_session'   # 設置存儲session的Mongo數據庫名
    SESSION_MONGODB_COLLECT = 'sessions'   # 設置存儲session的Mongo文檔名
    SESSION_SQLALCHEMY = SQLAlchemy()      # 設置SQLAlchemy映射數據庫
    SESSION_SQLALCHEMY_TABLE = 'sessions'  # 設置SQLAlchemy的表名


    SESSION_COOKIE_NAME = 'session'        # 設置session名爲App1-cookie
    SESSION_COOKIE_DOMAIN = ''             # 設置session的域名
    SESSION_COOKIE_PATH = '/'              # 設置session的路徑
    SESSION_COOKIE_HTTPONLY = True         # 設置session是否僅HTTP模式
    SESSION_COOKIE_SECURE = False          # 設置session是否加密
    delta = timedelta(                     # 設置session的過期時間
        days=50,
        seconds=20,
        microseconds=10,
        milliseconds=1000,
        minutes=5,
        hours=2,
        weeks=6,
    )
    PERMANENT_SESSION_LIFETIME = delta     # session的過期時間默認值:30days

模板層

模板是呈現給用戶的界面
在MVT中充當T的角色,實現了VT的解耦,開發中VT有這N:M的關係,
一個V可以調用任意T,一個T可以被任意V調用

模板處理分爲兩個過程
	1. 加載
	2. 渲染

模板代碼包含兩個部分
	1. 靜態HTML
	2. 動態插入的代碼段

Jinja2

Flask中使用Jinja2模板引擎
Jinja2由Flask作者開發
	一個現代化設計和友好的Python模板語言
	模仿Django的模板引擎

優點
	速度快,被廣泛使用
	HTML設計和後端Python分離
	減少Python複雜度
	非常靈活,快速和安全
	提供了控制,繼承等高級功能
	

模板語法

模板語法主要分爲兩種
	變量
	標籤
	
模板中的變量	{{   var  }}
	視圖傳遞給模板的數據
	前面定義出來的數據
	變量不存在,默認忽略

模板中的標籤	{% tag  %}
	控制邏輯
	使用外部表達式
	創建變量
	宏定義

結構標籤

block
	{% block xxx %}
	{% endblock %}
	塊操作
		父模板挖坑,子模板填坑	
		
extends
	{% extends ‘xxx’ %}

	繼承後保留塊中的內容
	{{ super() }}

挖坑繼承體現的是化整爲零的操作
include
	{% include ’xxx’ %}
	包含,將其他html包含進來,體現的是由零到一的概念

marco
	{% marco hello(name) %}
		{{ name }}
	{% endmarco %}
	宏定義,可以在模板中定義函數,在其它地方調用

宏定義可導入
	{% from ‘xxx’ import xxx %}

邏輯語句

—循環語句

<ul>
    {% for student in student_list %}
    <li>{{ student }}</li>
    {% endfor %}
</ul>

—選擇語句

{% if a==b %}
    <h1>a和b相等 a=b={{ a }}</h1>
{% endif %}

—循環中的loop

# loop 屬性
loop.first
loop.last
loop.length
loop.cycle
loop.index
loop.index0
loop.reindex
loop.reindex0
<ul>
{% for item in items %}
    {% if loop.first %}
     <li style="color: red">{{ item }}</li>
        {% elif loop.last %}
        <li style="color: blue">{{ item }}</li>
        {% else %}
        <li style="color: gold">{{ item }}</li>
    {% endif %}
{% endfor %}
</ul>

—實例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Student</title>
</head>
<body>
<ul>
    {% for student in student_list %}
    <li>{{ student }}</li>
    {% endfor %}
</ul>
<hr>
{% if a==b %}
    <h1>a和b相等 a=b={{ a }}</h1>
{% endif %}

{% if a!=b %}
    <h1>a和b不相等 a={{ a }} b={{ b }}</h1>
{% endif %}
</body>
</html>

繼承與導入

—覆蓋型繼承

{% extends 'user/register.html' %}
{% block content %}
    <b>繼承來自register.html的模板</b>
{% endblock %}

—不覆蓋型繼承

{% extends 'user/register.html' %}
{% block content %}
    {{ super() }}
    <b>繼承register.html後新添加的內容</b>
{% endblock %}

—導入模板

{% include 'part_demo.html' %}

宏定義

不傳參的函數定義
	{% macro hi()%}
	<b></b>
	{% endmacro %}
	
傳參的函數定義
	{% macro hello(name)%}
	<b>你好{{name}}</b>
	{% endmacro %}

導入函數
{{% from 'html_func.html' import hello,hi %}}

調用函數
{{hi()}}
{{ hello('Tom') }}

過濾器

語法  
	{{  變量|過濾器|過濾器… }}

capitalize
lower
upper
title
trim
reverse
format
striptags 渲染之前,將值中標籤去掉
safe
default
last
first
length
sum
sort

Bootstrap

https://blog.csdn.net/qq_44647926/article/details/103911134

模型層

數據庫知識

ORM

Flask默認並沒有提供任何數據庫操作的API
我們可以選擇任何適合自己項目的數據庫來使用
Flask中可以自己的選擇數據,用原生語句實現功能,也可以選擇ORM(SQLAlchemy,MongoEngine)

原生SQL缺點
	代碼利用率低,條件複雜代碼語句越長,有很多相似語句
	一些SQL是在業務邏輯中拼出來的,修改需要了解業務邏輯
	直接寫SQL容易忽視SQL問題

ORM優點
	將對對象的操作轉換爲原生SQL,易用性,可以有效減少重複SQL
	性能損耗少
	設計靈活,可以輕鬆實現複雜查詢
	移植性好

python的ORM(SQLAlchemy)
針對於Flask的支持
	pip install flask-sqlalchemy

URI通用格式

數據庫連接
	dialect+driver://username:password@host:port/database

dialect:數據庫實現
driver:數據庫的驅動
username:用戶名
password:密碼
host:主機
port:端口
database:數據庫名

連接MySQL數據庫

USERNAME=‘root’
PASSWORD=‘rock1204’
HOSTNAME = ’localhost’
PORT=3306’
DATABASE=‘HelloFlask’

DB_URI=‘mysql+pymsql://{}:{}@{}:{}/{}.format(
	USERNAME,
	PASSWORD,
	HOSTNAME,
	PORT,
	DATABASE)

字段類型

Integer			
SmallInteger		
BigInteger		
Float
Numeric
String
Text
Unicode
Unicode Text
Boolean
Date
Time
DateTime
Interval
LargeBinary

約束

primary_key
autoincrement
unique
index
nullable
default

ForeignKey()

模型的操作

1.安裝擴展模塊

pip install flask-script
pip install flask_migrate

2.添加db命令參數到Manager

# manage.py
from flask_script import Manager
from flask_migrate import MigrateCommand
from App import create_app

# 創建初始化插件和配置後的app對象
app = create_app(env)

# 將app傳入Manager中創建manager對象
manager = Manager(app=app)

# 將數據庫模型的遷移命令添加至manager對象中
manager.add_command('db',MigrateCommand)

3.創建模型

# models.py
class User(db.Model):
	__tablename__="user_tb" # 自定義表名 默認表名爲類名的小寫
	id = db.Column(db.Integer,primary_key=True)
	name = db.Column(db.String(16),unique=True)

4.生成模型遷移文件

python manage.py db migrate
  • 若是第一次使用db命令,先執行python manage.py db init 進行初始化。

5.將模型同步到服務器

python manage.py db upgrade

6.python manage.py db xx 命令可選參數

positional arguments:
  {init,revision,migrate,edit,merge,upgrade,downgrade,show,history,heads,branches,current,stamp}
    init                Creates a new migration repository
    revision            Create a new revision file.
    migrate             Alias for 'revision --autogenerate'
    edit                Edit current revision.
    merge               Merge two revisions together. Creates a new migration
                        file
    upgrade             Upgrade to a later version
    downgrade           Revert to a previous version
    show                Show the revision denoted by the given symbol.
    history             List changeset scripts in chronological order.
    heads               Show current available heads in the script directory
    branches            Show current branch points
    current             Display the current revision for each database.
    stamp               'stamp' the revision table with the given revision;
                        don't run any migrations

optional arguments:
  -?, --help            show this help message and exit

數據庫操作

引入相關對象

from ..ext import db
from ..models import User
from flask import Blueprint
blue = Blueprint('blue',__name__)

添加

# blue.py
# 添加單條數據
@blue.route('/add_user/')
def add_user():
	user = User()
	user.id = 1
	user.name = 'Tom'
	db.session.add(user)
	db.session.commit()
	return 'Add user success!'
	
# 添加多條數據
@blue.route("/add_users/")
def add_users():
    users = []
    for i in range(1,6):
        user = User()
        user.name = "用戶%s" % i
        users.append(user)
    db.session.add_all(users)
    db.session.commit()
    return "Add users success!"

刪除

# blue.py
@blue.route('/delete_user/')
def delete_user():
	user = User.query.first()
    db.session.delete(user)
    db.session.commit()
    return "Delete user success!"

更改

# blue.py
@blue.route('/update_user/')
def update_user():
	user = User.query.first()
	user.id = user.id + 1
	user.name = '用戶:'+user.name
	db.session.add(user)
	db.session.commit()
	return 'Update user success!'

查詢

# blue.py
# 條件查詢
@blue.route('/condition_query/')
def condition_query():
	'''運算符'''
	user = User.query.filter(User.id > 1)
	#user = User.query.filter(User.id < 1)
	#user = User.query.filter(User.id == 1)
	#user = User.query.filter(User.id >= 1)
	#user = User.query.filter(User.id <= 1)
	
	user = User.query.filter(User.id.__gt__(1))
	#user = User.query.filter(User.id.__lt__(1))
	#user = User.query.filter(User.id.__eq__(1))
	#user = User.query.filter(User.id.__ge__(1))
	#user = User.query.filter(User.id.__le__(1)).all()
	
    # user = User.query.filter(User.name=="Tom")
    # user = User.query.filter(User.name.contains("m"))
    # user = User.query.filter(User.name.startswith("T"))
    # user = User.query.filter(User.name.endswith("m"))
    # user = User.query.filter(User.name.like("To_%"))
    # user = User.query.filter(User.id.in_(User.query.filter()))


	print('學號:',user.id)
	print('姓名:',user.name)
	return 'Query user success!'

創建數據庫

db.create_all()

刪除數據庫

db.drop_all()

數據查詢

運算符

運算符
	contains
	startswith
	endswith
	in_
	like
	__gt__
	__ge__
	__lt__
	__le__

篩選
	filter_by()
	offset()
	limit()
	order_by()
	get()
	first()
	paginate()

邏輯運算
	與
		and_
		filter(and_(條件),條件…)
	或
		or_
		filter(or_(條件),條件…)
	非
		not_
		filter(not_(條件),條件…)

鉤子函數

before_request,after_request

1.在app中調用before_request,after_request

# App/middleware.py
def load_middleware(app):

    @app.before_request
    def before():
        """
        before_request一般用途:
                        統計
                        優先級
                        反爬蟲
                        用戶認證
                        用戶權限
        """
        print("請求報文處理之前,執行該函數")
        print(request.url)
        
    @app.after_request
    def after(res):
        """
        after_request一般用途:
                        響應報文的處理
        """
        print("請求報文處理完成之後,返回響應報文之前,執行該函數")
        print(type(res))
        print(res)

        return res # 必須返回一個<class 'flask.wrappers.Response'>類型
# App/__init__.py
......
......
from App.middleware import load_middleware

def create_app(env):
	......
	......

    # 加載中間件
    load_middleware(app)

    return app

2.在blue中調用before_request,after_request

# App/views/blue.py
@blue.before_request
def before():
	print("請求報文處理之前,執行該函數")

@blue.after_request
def ater(res):
	print("請求報文處理完成之後,返回響應報文之前,執行該函數")
    return res # 此處的res響應報文會返回客戶端
  • after_request必須返回一個<class 'flask.wrappers.Response'>類型

四大對象中的g,config

1.在視圖函數中傳入g使用

# App/views/blue.py
@blue.before_request
def before():
    # from flask import g
    g.msg = "此變量用於在不同的函數間傳遞"

@blue.route("/test_g/")
def test_g():
    return g.msg,200

2.在模板中直接使用g

# App/views/blue.py
@blue.route("/test_g/")
def test_g():
    g.msg = "此變量用於在不同的函數間傳遞"
    return render_template("test.html")
# App/templates/test.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <li>{{ g.msg }}</li>

</body>
</html>

3.在視圖函數中傳入config使用

# App/views/blue.py
@blue.route("/test_config/")
def test_g():
    # from flask import current_app
    # current_app對象需要在app初始化後纔可調用
    return render_template("test.html",config=current_app.config)
  • from flask import current_app
  • current_app對象需要在app初始化後纔可調用
# App/templates/test.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {% for c in config %}
        <li>{{ c }}={{ config[c] }}</li>
    {% endfor %}

</body>
</html>

4.在模板中直接使用config

# App/views/blue.py
@blue.route("/test_config/")
def test_g():
    return render_template("test.html")
# App/templates/test.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {% for c in config %}
        <li>{{ c }}={{ config[c] }}</li>
    {% endfor %}

</body>
</html>

其他

文件傳輸

# 服務器接收文件
@blue.route("/upload_img/", methods=['POST'])
def receive_file():
    upload_file = request.files['file']
    old_file_name = upload_file.filename
    file_path = "./upload/image/"+old_file_name
    if upload_file:
        upload_file.save(file_path)
        return 'Upload success!'
    else:
        return 'Upload failed!'
# 客戶端文件上傳
def upload_file(upload_url,file_path):
	import requests
	import os
	# 定義文件路徑
	split_path = file_path.split('\\')
	filename = split_path[-1]
	# 獲取文件大小
	filesize = os.path.getsize(file_path)/1024**2
	# 輸出詳細信息
	print("文件路徑:%s"%file_path)
	print("文件名:%s"%filename)
	print("文件大小:%s M"%str(round(filesize,2)))
	print("文件狀態:上傳中...")
	# 打開文件進行數據傳輸
	with open(file_path, 'rb') as f:
		files = {'file':(filename, f, '*/*')}
		r = requests.post(upload_url,files = files)
		if r.status_code == 200:
			print("上傳成功!")
		else:
			print("上傳失敗!")

upload_file("http://127.0.0.1:5000/upload_img/",r"C:\Users\Mr.m\Desktop\Python\Python3網絡爬蟲開發實戰.pdf")
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章