Python3+Flask初学教程

目录

一、学习文档

二、项目结构

三、项目文件

四、效果展示

1、登录页面

2、首页页面

3、上传文件

4、查询数据库

5、404页面

一、学习文档

Flask 依赖 Jinja 模板引擎和 Werkzeug WSGI 套件

W3Cschool:https://www.w3cschool.cn/flask/

Flask中文文档:https://dormousehole.readthedocs.io/en/latest/

Jinja2 模板文档:https://jinja.palletsprojects.com/en/2.11.x/templates/

Werkzeug 文档:https://werkzeug.palletsprojects.com/en/1.0.x/

Flask应用功能扩展:https://dormousehole.readthedocs.io/en/latest/extensions.html#extensions

Flask生产环境部署:https://dormousehole.readthedocs.io/en/latest/deploying/index.html#deployment

二、项目结构

pycharm新建Flask项目之后添加或修改如下项目文件

Python3+Flask初学教程

三、项目文件

404.html

    <h1>404 error</h1>
    <a href="{{ url_for('index') }}">index</a> 

hello.html

<title>Hello from Flask</title>
{% if name %}
  <h1>Hello {{ name }}!</h1>
{% else %}
  <h1>Hello, World!</h1>
{% endif %}
    <a href="{{ url_for('index') }}">index</a> 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Welcome to Flask!</title>
    <!-- Flask加载静态资源 -->
    <script type="text/javascript" src="{{ url_for('static', filename = 'js/hello.js') }}"></script>
</head>
<body>
    <h1>Welcome to Flask!</h1>
    <input type="button" onclick="sayHello()" value="Say Hello">
    {% with messages = get_flashed_messages() %}
         {% if messages %}
               {% for message in messages %}
                    <p>{{ message }}</p>
               {% endfor %}
         {% endif %}
    {% endwith %}
    <a href="{{ url_for('set_cookie') }}">set_cookie</a> 
    <a href="{{ url_for('get_cookie') }}">get_cookie</a> 
    <a href="{{ url_for('del_cookie') }}">del_cookie</a> 
    <a href="{{ url_for('login') }}">login</a> 
    <a href="{{ url_for('upload_file') }}">upload</a> 
    <a href="student.html">student</a> 
    <b><a href="mysqldb.html">mysqldb</a></b> 
    <b><a href="{{ url_for('logout') }}">&#x70B9;&#x51FB;&#x8FD9;&#x91CC;&#x6CE8;&#x9500;</a></b> 
    <a href="404.html">404</a> 
</body>
</html>

kv-result.html

  <table border="1">
     {% for key, value in result.items() %}
    <tr>
       <th> {{ key }} </th>
       <td> {{ value }}</td>
    </tr>
 {% endfor %}
  </table>
  <a href="{{ url_for('index') }}">index</a> 

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
    <form method="post" action="http://localhost:5000/login">
        <table>
            <tr>
                <td>Username</td>
                <td><input type="username" name="username"></td>
            </tr>
            <tr>
                <td>Password</td>
                <td><input type="password" name="password"></td>
            </tr>
            <tr>
                <td><input type="submit" value="Submit"></td>
            </tr>
        </table>
    </form>
    {% if error %}
        <p><strong>Error</strong>: {{ error }}</p>
    {% endif %}
</body>
</html>

mysqldb.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>mysql_db</title>
</head>
<body>
  <form action="/mysql_db" method="POST">
     <p>ip:<input type="text" name="ip" value="127.0.0.1"></p>
     <p>port:<input type="text" name="port" value="3306"></p>
     <p>username:<input type="text" name="username" value="root"></p>
     <p>password:<input type="text" name="password" value="123456"></p>
     <p><input type="submit" value="submit"></p>
  </form>
    <a href="{{ url_for('index') }}">index</a> 
</body>
</html>

result.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
  <table border="1">
     {% for value in result %}
    <tr>
{#       <th> {{ key }} </th>#}
       <td> {{ value }}</td>
    </tr>
 {% endfor %}
  </table>
  <a href="{{ url_for('index') }}">index</a> 
</body>
</html>

student.html

  <form action="/kv-result" method="POST">
     <p>Name <input type="text" name="Name" value="Name"></p>
     <p>Physics <input type="text" name="Physics" value="Physics"></p>
     <p>Chemistry <input type="text" name="chemistry" value="chemistry"></p>
     <p>Maths <input type="text" name="Mathematics" value="Mathematics"></p>
     <p><input type="submit" value="submit"></p>
  </form>

upload.html

    <h1>Upload new File</h1>
    <form method="post" enctype="multipart/form-data">
      <input type="file" name="file">
      <input type="submit" value="Upload">
    </form>
    <a href="{{ url_for('index') }}">index</a> 

app.py

import os, json
from flask import Flask, render_template, flash, request, redirect, jsonify, session
from flask import escape, url_for, make_response, abort
from werkzeug.utils import secure_filename
from utils.db.MySQLUtil import MySQLUtil

UPLOAD_FOLDER = './'
ALLOWED_EXTENSIONS = {'txt', 'log', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
app = Flask(__name__)

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'

@app.route('/index', methods=['GET', 'POST'])
def index():
    """&#x8BF7;&#x6C42;&#x65B9;&#x6CD5;&#x548C;cookie"""
    method = request.method
    username = request.cookies.get('username')
    print(method, username)
    return render_template('index.html', name="name_welcome")

@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
    """&#x53D8;&#x91CF;&#x89C4;&#x5219;"""
    return render_template('hello.html', name=name)

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    """&#x6587;&#x4EF6;&#x4E0A;&#x4F20;"""
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return render_template('upload.html')
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            flash('upload file success')
            return url_for('upload_file', filename=filename)
    return render_template('upload.html')

@app.route('/match/<str>')
def match_url(str):
    """url&#x6784;&#x5EFA;"""
    print('{}\'s profile'.format(escape(str)))
    return render_template(str+".html")

@app.route('/<str>')
def url_forward(str):
    """url&#x6784;&#x5EFA;"""
    return render_template(str)

@app.route('/set_cookie')
def set_cookie():
    """&#x5B58;&#x50A8;cookie"""
    response = make_response("set cookie success")
    response.set_cookie('username', 'the username')
    flash(str(response))
    return redirect(url_for('index'))

@app.route('/get_cookie')
def get_cookie():
    """&#x8BFB;&#x53D6;cookie"""
    cookie = request.cookies.get('username')
    flash(cookie)
    return redirect(url_for('index'))

@app.route("/del_cookie")
def del_cookie():
    """&#x5220;&#x9664;cookie&#xFF08;&#x5220;&#x9664;&#x53EA;&#x662F;&#x8BA9;cookie&#x8FC7;&#x671F;&#xFF09;"""
    response = make_response("delete cookie success")
    response.delete_cookie("username")
    flash(str(response))
    return redirect(url_for('index'))

@app.route('/')
def my_redirect():
    return redirect(url_for('login'))

@app.errorhandler(404)
def page_not_found(error):
    """404&#x72B6;&#x6001;&#x8FD4;&#x56DE;&#x7F51;&#x9875;"""
    return render_template('404.html'), 404

@app.route('/login', methods = ['GET', 'POST'])
def login():
    """&#x6D88;&#x606F;&#x95EA;&#x73B0;"""
    error = None
    if request.method == 'POST':
        if request.form['username'] != 'admin': ## or request.form['password'] != 'admin':
           error = "Invalid username or password. Please try again!"
        else:
           flash('You were successfully logged in')
           return redirect(url_for('index'))
    return render_template('login.html', error=error)

@app.route('/logout')
def logout():
    """&#x5220;&#x9664;session&#x4E2D;&#x7684;username"""
    session.pop('username', None)
    return redirect(url_for('login'))

@app.route('/kv-result', methods=['POST', 'GET'])
def result():
    """&#x5C06;&#x8868;&#x5355;&#x6570;&#x636E;&#x8FD4;&#x56DE;&#x7ED9;&#x6A21;&#x677F;"""
    if request.method == 'POST':
      result = request.form
      print(result)
      return render_template("kv-result.html", result=result)

@app.route('/mysql_db', methods=['POST', 'GET'])
def mysql_db():
    """&#x67E5;&#x8BE2;MySQL&#x5168;&#x90E8;&#x6570;&#x636E;&#x5E93;&#x540D;&#x79F0;"""
    if request.method == 'POST':
      form = request.form
      print(type(form), form)
      ip = form['ip']
      port = form['port']
      username = form['username']
      password = form['password']
      print(ip, port, username, password)
      mysqlUtil = MySQLUtil(ip, port, username, password)
      dbs = mysqlUtil.list_databases()
      print(dbs)
      return render_template("result.html", result=dbs)

if __name__ == '__main__':
    print(1111)
    app.run(host='0.0.0.0', port='5000', debug=True, threaded=True)
    app.logger.debug('A value for debugging')
    app.logger.warning('A warning occurred (%d apples)', 42)
    app.logger.error('An error occurred')
    print(2222)
</str></str></name>

flash.py

#-*- encoding: utf-8 -*-

from flask import Flask, flash, redirect, render_template, request, url_for
app = Flask(__name__)

app.secret_key = 'random string'

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

@app.route('/login', methods = ['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form['username'] != 'admin' or \
            request.form['password'] != 'admin':
            error = 'Invalid username or password. Please try again!'
        else:
            flash('You were successfully logged in')
            return redirect(url_for('index'))
    return render_template('login.html', error=error)

if __name__ == "__main__":
    app.run(debug=True)

四、效果展示

执行 app.py 启动程序,浏览器访问 http://127.0.0.1:5000/login

1、登录页面

输入用户名:admin(密码随意)

Python3+Flask初学教程

2、首页页面

Python3+Flask初学教程

3、上传文件

Python3+Flask初学教程

4、查询数据库

Python3+Flask初学教程

5、404页面

Python3+Flask初学教程

Original: https://blog.csdn.net/qq262593421/article/details/114524619
Author: 日月星辰TEL
Title: Python3+Flask初学教程

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/749572/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球