当前位置 博文首页 > qq262593421的博客:Python3+Flask初学教程

    qq262593421的博客:Python3+Flask初学教程

    作者:[db:作者] 时间:2021-08-17 21:44

    目录

    一、学习文档

    二、项目结构

    三、项目文件

    四、效果展示

    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项目之后添加或修改如下项目文件

    三、项目文件

    404.html

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

    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> <br/>

    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> <br/>
        <a href = "{{ url_for('get_cookie') }}">get_cookie</a> <br/>
        <a href = "{{ url_for('del_cookie') }}">del_cookie</a> <br/>
        <a href = "{{ url_for('login') }}">login</a> <br/>
        <a href = "{{ url_for('upload_file') }}">upload</a> <br/>
        <a href = "student.html">student</a> <br/>
        <b><a href = 'mysqldb.html'>mysqldb</a></b> <br/>
        <b><a href = "{{ url_for('logout') }}">点击这里注销</a></b> <br/>
        <a href = "404.html">404</a> <br/>
    </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> <br/>

    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> <br/>
    </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> <br/>
    </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> <br/>

    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():
        """请求方法和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):
        """变量规则"""
        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():
        """文件上传"""
        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构建"""
        print('{}\'s profile'.format(escape(str)))
        return render_template(str+".html")
    
    @app.route('/<str>')
    def url_forward(str):
        """url构建"""
        return render_template(str)
    
    @app.route('/set_cookie')
    def set_cookie():
        """存储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():
        """读取cookie"""
        cookie = request.cookies.get('username')
        flash(cookie)
        return redirect(url_for('index'))
    
    @app.route("/del_cookie")
    def del_cookie():
        """删除cookie(删除只是让cookie过期)"""
        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状态返回网页"""
        return render_template('404.html'), 404
    
    @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)
    
    @app.route('/logout')
    def logout():
        """删除session中的username"""
        session.pop('username', None)
        return redirect(url_for('login'))
    
    @app.route('/kv-result', methods=['POST', 'GET'])
    def result():
        """将表单数据返回给模板"""
        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():
        """查询MySQL全部数据库名称"""
        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)
    

    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(密码随意)

    2、首页页面

    3、上传文件

    4、查询数据库

    5、404页面

    cs