CS50 lab9 利用Flask实现一个简单的带表格和表单的网页

Create a web application to keep track of friends’ birthdays.

 

Getting Started

Here’s how to download this lab into your own CS50 IDE. Log into CS50 IDE and then, in a terminal window, execute each of the below.

  • Execute cd to ensure that you’re in ~/ (i.e., your home directory, aka ~).
  • Execute wget https://cdn.cs50.net/2020/fall/labs/9/lab9.zip to download a (compressed) ZIP file with this problem’s distribution.
  • Execute unzip lab9.zip to uncompress that file.
  • Execute rm lab9.zip followed by yes or y to delete that ZIP file.
  • Execute ls. You should see a directory called lab9, which was inside of that ZIP file.
  • Execute cd lab9 to change into that directory.
  • Execute ls. You should see an application.py file, a birthdays.db file, a static directory, and a templates directory.

Understanding

In application.py, you’ll find the start of a Flask web application. The application has one route (/) that accepts both POST requests (after the if) and GET requests (after the else). Currently, when the / route is requested via GET, the index.html template is rendered. When the / route is requested via POST, the user is redirected back to / via GET.

birthdays.db is a SQLite database with one table, birthdays, that has four columns: idnamemonth, and day. There are a few rows already in this table, though ultimately your web application will support the ability to insert rows into this table!

In the static directory is a styles.css file containing the CSS code for this web application. No need to edit this file, though you’re welcome to if you’d like!

In the templates directory is an index.html file that will be rendered when the user views your web application.

Implementation Details

Complete the implementation of a web application to let users store and keep track of birthdays.

  • When the / route is requested via GET, your web application should display, in a table, all of the people in your database along with their birthdays.
    • First, in application.py, add logic in your GET request handling to query the birthdays.db database for all birthdays. Pass all of that data to your index.html template.
    • Then, in index.html, add logic to render each birthday as a row in the table. Each row should have two columns: one column for the person’s name and another column for the person’s birthday.
  • When the / route is requested via POST, your web application should add a new birthday to your database and then re-render the index page.
    • First, in index.html, add an HTML form. The form should let users type in a name, a birthday month, and a birthday day. Be sure the form submits to / (its “action”) with a method of post.
    • Then, in application.py, add logic in your POST request handling to INSERT a new row into the birthdays table based on the data supplied by the user.

Optionally, you may also:

  • Add the ability to delete and/or edit birthday entries.
  • Add any additional features of your choosing!

Hints

  • Recall that you can call db.execute to execute SQL queries within application.py.
    • If you call db.execute to run a SELECT query, recall that the function will return to you a list of dictionaries, where each dictionary represents one row returned by your query.
  • You’ll likely find it helpful to pass in additional data to render_template() in your index function so that access birthday data inside of your index.html template.
  • Recall that the tr tag can be used to create a table row and the td tag can be used to create a table data cell.
  • Recall that, with Jinja, you can create a for loop inside your index.html file.
  • In application.py, you can obtain the data POSTed by the user’s form submission via request.form.get(field) where field is a string representing the name attribute of an input from your form.
    • For example, if in index.html, you had an <input name="foo" type="text">, you could use request.form.get("foo") in application.py to extract the user’s input.

Testing

No check50 for this lab! But be sure to test your web application by adding some birthdays and ensuring that the data appears in your table as expected.

Run flask run in your terminal while in your lab9 directory to start a web server that serves your Flask application.

 

 

首先,由于项目提供源代码为了降低难度使用了封装好的数据库,我们在本地运行的时候,需要查阅文档,把SQLite3数据库链接部分添加出来

DATABASE = 'birthdays.db'

def get_db():
    db = getattr(g, '_database', None)
    if db is None:
        db = g._database = sqlite3.connect(DATABASE)
    return db

@app.teardown_appcontext
def close_connection(exception):
    db = getattr(g, '_database', None)
    if db is not None:
        db.close()

然后,我们实现Get逻辑

@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "POST":

        # TODO: Add the user's entry into the database

        return redirect("/")

    else:
        # Display the entries in the database on index.html
        birthdays = get_db().execute("SELECT * FROM birthdays")
        #print(birthdays)
        return render_template("index.html", birthdays = birthdays)

HTML使用了模版技术,所以我们修改对应部分的HTML代码

            <div class="section">

                <h2>All Birthdays</h2>
                <table>
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Birthday</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- TODO: Loop through the database entries to display them in this table -->
                        {% for birthday in birthdays %}
                        <tr>
                            <td>{{birthday.name}}</td>
                            <td>{{birthday.month}}/{{birthday.day}}</td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>

写一个输入框表单

            <div class="section">
                <h2>Add a Birthday</h2>
                <!-- TODO: Create a form for users to submit a name, a month, and a day -->
                <form action='/' method="post">
                    <input name='name' placeholder="Name" type='text'>
                    <input name='month' placeholder="Month" type='number' min=1 max=12>
                    <input name='day' placeholder="Day" type='number' min=1 max=31>
                    <input type="submit" value="Add Birthday">

                </form>
            </div>

然后POST请求拿到表单数据入库

def index():
    if request.method == "POST":

        # TODO: Add the user's entry into the database
        name = request.form.get("name")
        month = request.form.get("month")
        day = request.form.get("day")
        get_db().execute("INSERT INTO birthdays (name, month, day) VALUES(?, ?, ?)", name, month, day)
        return redirect("/")

Flask数据库连接有一些bug

import os

import sqlite3
from contextlib import closing
from typing import Mapping
from flask import Flask, flash, jsonify, redirect, render_template, request, session, g

DATABASE = "./birthdays.db"

# Configure application
app = Flask(__name__)
app.config.from_object(__name__)

# Ensure templates are auto-reloaded
app.config["TEMPLATES_AUTO_RELOAD"] = True



def connect_db():
    return sqlite3.connect(app.config['DATABASE'])
 
@app.before_request
def before_request():
    g.db = connect_db()
 
 
@app.after_request
def after_request(response):
    g.db.close()


@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "POST":

        # TODO: Add the user's entry into the database
        name = request.form.get("name")
        month = request.form.get("month")
        day = request.form.get("day")
        #print(name + " " + month + " " + day + "\n")
        g.db.execute("INSERT INTO birthdays (name, month, day) VALUES(?, ?, ?)", (name, month, day))
        return redirect("/")

    else:
        # Display the entries in the database on index.html
        cur = g.db.execute("SELECT * FROM birthdays")
        birthdays = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]
        return render_template("index.html", birthdays = birthdays)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值