最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

一步步講解利用Flask開發(fā)一個Web程序

 更新時間:2025年02月26日 09:39:39   作者:幸運Cookie  
這篇文章主要介紹了使用Flask框架在Linux系統(tǒng)上開發(fā)一個簡單的WatchList?Web程序的過程,包括了實現(xiàn)的詳細步驟,最終實現(xiàn)了一個包含登錄界面的Web程序,需要的朋友可以參考下

開發(fā)環(huán)境 : Linux系統(tǒng),語言: Python,Html, Css

利用Flask實現(xiàn)一個WatchList的Web程序,部分代碼和圖片都是來自:Flask 入門教程,我在此基礎(chǔ)上修改了一下,最后的效果如下:

1. 安裝 Flask和一些基本插件

pip install flask
pip install Flask-SQLAlchemy
pip install pymysql

如果安裝比較慢的話,可以加上 -i https://pypi.tsinghua.edu.cn/simple

2. 創(chuàng)建項目結(jié)構(gòu)

創(chuàng)建一個文件夾來存放你的項目文件。項目的基本結(jié)構(gòu)如下:

WatchList/{static/images style.css} {template/index.html login.html} app.py

3.在WatchList目錄下創(chuàng)建虛擬環(huán)境并進入虛擬環(huán)境

python3 -m venv env
scoure ./env/Scripts/activate

4. 編寫主應(yīng)用文件 (app.py)

在 WatchList目錄下創(chuàng)建一個名為 app.py 的文件,并編寫以下代碼:

from flask import Flask, render_template, url_for, redirect, request, flash
from flask_sqlalchemy import SQLAlchemy
import click

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@localhost/watchlist'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = 'your_secret_key'  # 用于閃現(xiàn)消息

db = SQLAlchemy(app)

# 創(chuàng)建數(shù)據(jù)庫命令
@app.cli.command()
def forge():
    """Generate fake data."""
    db.create_all()

    name = 'BrokenOfViolet'
    movies = [
        {'title': 'My Neighbor Totoro', 'year': '1988'},
        {'title': 'Dead Poets Society', 'year': '1989'},
        {'title': 'A Perfect World', 'year': '1993'},
        {'title': 'Leon', 'year': '1994'},
        {'title': 'Mahjong', 'year': '1996'},
        {'title': 'Swallowtail Butterfly', 'year': '1996'},
        {'title': 'King of Comedy', 'year': '1999'},
        {'title': 'Devils on the Doorstep', 'year': '1999'},
        {'title': 'WALL-E', 'year': '2008'},
        {'title': 'The Pork of Music', 'year': '2012'},
    ]

    user = User(username=name, password='password123')  # 設(shè)定一個默認密碼
    db.session.add(user)
    for m in movies:
        movie = Movie(title=m['title'], year=m['year'])
        db.session.add(movie)

    db.session.commit()
    click.echo('Done.')

# 數(shù)據(jù)庫模型
class User(db.Model):
    username = db.Column(db.String(20), primary_key=True)
    password = db.Column(db.String(20))

class Movie(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(60))
    year = db.Column(db.String(4))

# 主頁路由
@app.route('/')
def index():
    user = User.query.first()  # 修復此處變量名
    movies = Movie.query.all()
    return render_template("index.html", user=user, movies=movies)

# 404 錯誤處理路由
@app.errorhandler(404)
def page_not_found(e):
    user = User.query.first()
    return render_template('404.html', user=user), 404

# 登錄路由
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        user = User.query.filter_by(username=username).first()

        # 比對用戶輸入的密碼和數(shù)據(jù)庫中存儲的密碼
        if user and user.password == password:
            flash('Login successful!', 'success')
            return redirect(url_for('index'))  # 假設(shè)登錄成功后重定向到index
        else:
            flash('Invalid username or password.', 'danger')

    return render_template('login.html')

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

5. 創(chuàng)建 HTML 模板文件

  • 主頁templates/index.html

 在 templates 目錄中創(chuàng)建一個名為 index.html 的文件,編寫一個簡單的 HTML 頁面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="{{url_for('static',filename='style.css')}}" rel="external nofollow"  type="text/css">
    <title>{{ name }}'s Watchlist</title>
</head>
<body>
    <h2>{{ name }}'s Watchlist
        <img alt="Avatar" class="avator" src="{{url_for('static',filename='images/avatar.png')}}">
    </h2>
    {# 使用 length 過濾器獲取 movies 變量的長度 #}
    <p>{{ movies|length }} Titles</p>
    <ul class="movie-list">
        {% for movie in movies %}  {# 迭代 movies 變量 #}
        <li>{{ movie.title }} - {{ movie.year }}</li>  {# 等同于 movie['title'] #}
        {% endfor %}  {# 使用 endfor 標簽結(jié)束 for 語句 #}
    </ul>
    <img alt="Totoro" class="totoro" src="{{url_for('static',filename='images/totoro.gif')}}"
</body>
</html>
  • 登陸界面templates/login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}" rel="external nofollow" >
</head>
<body>
    <div class="login-container">
        <h2>Login</h2>
        {% with messages = get_flashed_messages(with_categories=true) %}
          {% if messages %}
            <ul class="flashes">
              {% for category, message in messages %}
                <li class="{{ category }}">{{ message }}</li>
              {% endfor %}
            </ul>
          {% endif %}
        {% endwith %}
        <form method="post" action="{{ url_for('login') }}">
            <div class="input-group">
                <label for="username">Username</label>
                <input type="text" id="username" name="username" required>
            </div>
            <div class="input-group">
                <label for="password">Password</label>
                <input type="password" id="password" name="password" required>
            </div>
            <button type="submit">Login</button>
        </form>
    </div>
</body>
</html>

6. 創(chuàng)建靜態(tài)文件 (static/style.css)

在 static 目錄中創(chuàng)建一個名為 style.css 的文件,添加一些簡單的 CSS 樣式:

/* 頁面整體 */
body {
    font-family: Arial, sans-serif;
    background-color: #f0f0f0;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
}

/* 頁腳 */
footer {
    color: #888;
    margin-top: 15px;
    text-align: center;
    padding: 10px;
}

/* 頭像 */
.avatar {
    width: 40px;
}

/* 電影列表 */
.movie-list {
    list-style-type: none;
    padding: 0;
    margin-bottom: 10px;
    box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12);
}

.movie-list li {
    padding: 12px 24px;
    border-bottom: 1px solid #ddd;
}

.movie-list li:last-child {
    border-bottom:none;
}

.movie-list li:hover {
    background-color: #f8f9fa;
}

/* 龍貓圖片 */
.totoro {
    display: block;
    margin: 0 auto;
    height: 100px;
}

.login-container {
    background-color: white;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    width: 300px;
    text-align: center;
}

h2 {
    margin-bottom: 20px;
}

.input-group {
    margin-bottom: 15px;
    text-align: left;
}

.input-group label {
    display: block;
    margin-bottom: 5px;
}

.input-group input {
    width: 100%;
    padding: 8px;
    box-sizing: border-box;
}

button {
    width: 100%;
    padding: 10px;
    background-color: #007BFF;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 16px;
}

button:hover {
    background-color: #0056b3;
}

.flashes {
    list-style-type: none;
    padding: 0;
}

.flashes li {
    padding: 10px;
    margin-bottom: 10px;
    border-radius: 5px;
}

.flashes li.success {
    background-color: #d4edda;
    color: #155724;
}

.flashes li.danger {
    background-color: #f8d7da;
    color: #721c24;
}

7. 運行應(yīng)用

在終端中,導航到 WatchList 目錄并運行應(yīng)用。因為在app.py中定義了forge函數(shù)用于提交數(shù)據(jù),所以進行如下操作:

flask forge

最后直接運行 app.py 或者執(zhí)行 flask run

總結(jié)

到此這篇關(guān)于利用Flask開發(fā)一個Web程序的文章就介紹到這了,更多相關(guān)Flask開發(fā)Web程序內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 單身狗福利?Python爬取某婚戀網(wǎng)征婚數(shù)據(jù)

    單身狗福利?Python爬取某婚戀網(wǎng)征婚數(shù)據(jù)

    今天我就當回媒婆,給男性程序員來點福利.今天目標爬取征婚網(wǎng)上呈現(xiàn)出來的女生信息保存成excel表格供大家篩選心儀的女生,需要的朋友可以參考下
    2021-06-06
  • Python高階函數(shù)、常用內(nèi)置函數(shù)用法實例分析

    Python高階函數(shù)、常用內(nèi)置函數(shù)用法實例分析

    這篇文章主要介紹了Python高階函數(shù)、常用內(nèi)置函數(shù)用法,結(jié)合實例形式分析了Python高階函數(shù)與常用內(nèi)置函數(shù)相關(guān)功能、原理、使用技巧與操作注意事項,需要的朋友可以參考下
    2019-12-12
  • python中pywebview框架使用方法記錄

    python中pywebview框架使用方法記錄

    Pywebview是一個用于構(gòu)建網(wǎng)頁的Python庫,類似于Flask框架,但主要使用Python編寫而非HTML或JS,通過簡單的命令即可安裝和使用,支持創(chuàng)建自制或調(diào)用外部網(wǎng)頁界面,需要的朋友可以參考下
    2024-09-09
  • 保留已有python安裝Anaconda的方法推薦

    保留已有python安裝Anaconda的方法推薦

    在安裝Anaconda之前,有的已經(jīng)安裝過一個Python版本了,但是又不想刪除這個Python版本,該怎么辦呢??這篇文章主要給大家介紹了關(guān)于保留已有python安裝Anaconda的幾種法推薦,需要的朋友可以參考下
    2023-12-12
  • Python使用requests庫發(fā)送請求的示例代碼

    Python使用requests庫發(fā)送請求的示例代碼

    與原生的urllib庫相比,requests庫提供了更簡潔、易于理解和使用的API,使發(fā)送HTTP請求變得更加直觀和高效,所以本文給大家介紹了Python如何使用requests庫發(fā)送請求,需要的朋友可以參考下
    2024-03-03
  • python上下文管理的使用場景實例講解

    python上下文管理的使用場景實例講解

    在本篇文章里小編給大家整理的是一篇關(guān)于python上下文管理的使用場景實例講解內(nèi)容,有興趣的朋友們可以學習下。
    2021-03-03
  • python的廣播機制詳解

    python的廣播機制詳解

    大家好,本篇文章主要講的是python的廣播機制詳解,感興趣的同學趕快來看一看吧,對你有幫助的話記得收藏一下,方便下次瀏覽
    2022-01-01
  • Python使用docx模塊實現(xiàn)刷題功能代碼

    Python使用docx模塊實現(xiàn)刷題功能代碼

    今天小編就為大家分享一篇Python使用docx模塊實現(xiàn)刷題功能代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-02-02
  • Python爬蟲利用多線程爬取 LOL 高清壁紙

    Python爬蟲利用多線程爬取 LOL 高清壁紙

    這篇文章主要介紹了Python爬蟲利用多線程爬取 LOL 高清壁紙,通過網(wǎng)站爬取每一個英雄的所有皮膚圖片,全部下載下來并保存到本地,下文爬取過程感興趣的朋友可以參考一下
    2022-06-06
  • Python使用嵌套循環(huán)實現(xiàn)圖像處理算法

    Python使用嵌套循環(huán)實現(xiàn)圖像處理算法

    這篇文章主要給大家詳細介紹Python如何使用嵌套循環(huán)實現(xiàn)圖像處理算法,文中有詳細的代碼示例,具有一定的參考價值,需要的朋友可以參考下
    2023-07-07

最新評論

个旧市| 丰顺县| 娱乐| 于田县| 武宣县| 丁青县| 桐城市| 荆门市| 铜梁县| 靖西县| 鄂州市| 江永县| 文水县| 务川| 资中县| 华坪县| 仙桃市| 平凉市| 承德县| 治县。| 宁都县| 西平县| 汕头市| 攀枝花市| 新乡市| 漳平市| 平昌县| 白玉县| 喀喇沁旗| 沧州市| 合山市| 黑山县| 清河县| 沾益县| 榕江县| 恩平市| 固阳县| 肇庆市| 合山市| 手机| 富民县|