我是烧瓶新手。在我的检索请求中似乎出现了问题。我想从表中获取行,并按从邮寄请求中提取的选择值进行过滤。
这是我的希玛:
CREATE TABLE poll (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sex TEXT NOT NULL,
city TEXT NOT NULL,
emotion TEXT NOT NULL,
month TEXT NOT NULL,
poll_time TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
db.py:
import sqlite3
import click
from flask import current_app, g
from flask.cli import with_appcontext
def get_db():
if 'db' not in g:
g.db = sqlite3.connect(
current_app.config['DATABASE'],
detect_types=sqlite3.PARSE_DECLTYPES
)
g.db.row_factory = sqlite3.Row
return g.db
def close_db(e=None):
db = g.pop('db', None)
if db is not None:
db.close()
def init_db():
db = get_db()
with current_app.open_resource('schema.sql') as f:
db.executescript(f.read().decode('utf8'))
@click.command('init-db')
@with_appcontext
def init_db_command():
"""Clear the existing data and create new tables."""
init_db()
click.echo('Initialized the database.')
def init_app(app):
app.teardown_appcontext(close_db)
app.cli.add_command(init_db_command)
初始化 .py:
import os
from flask import Flask
from . import db
from . import routes
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
app.config.from_mapping(
SECRET_KEY='dev',
DATABASE=os.path.join(app.instance_path, 'flaskapp.sqlite'),
UPLOAD_FOLDER=os.path.join(os.getcwd(), 'uploads')
)
app.register_blueprint(routes.bp)
app.add_url_rule('/', endpoint='index')
# ensure the instance folder exists
try:
os.makedirs(app.instance_path)
except OSError:
pass
db.init_app(app)
return app
route.py:
from flask import (
Blueprint, g, redirect, render_template, request, url_for, flash, current_app
)
from flaskapp.db import get_db
from flaskapp.form import ChoiceForm
bp = Blueprint('routes', __name__)
@bp.route('/poll-process', methods=['POST', 'GET'])
def process():
form = ChoiceForm(request.form)
if request.method == 'POST':
sel1 = request.form.get('sel')
print(sel1)
req1 = get_db().execute(
'SELECT * FROM poll WHERE sex = ?',
(sel1,)
).fetchall()
print(req1)
return render_template('process.html', form=form)
form.py:
from wtforms import Form, SelectField, SelectMultipleField, RadioField, SubmitField, validators
sel_choice1 = [
('m', 'man'),
('w', 'woman'),
]
class ChoiceForm(Form):
sel_sex = SelectField(u'Criteria', choices=sel_choice1)
radio = RadioField(choices=[('csv', 'csv'), ('html', 'html')])
submit = SubmitField(label='apply')
form.html:
<form method="post">
<!-- select -->
<div class="form-group mt-4">
<h2>Choose criteria to sort</h2>
<!-- sex -->
<select class="custom-select" name="sel"> <!-- multiple -->
{% for field in form.sel_sex %}
<option>{{ field }}</option>
{% endfor %}
</select>
...
</div>
<!-- submit -->
{{form.submit(class="btn btn-primary")}}
</form>
* Serving Flask app "flaskapp" (lazy loading)
* Environment: development
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 231-471-963
m
127.0.0.1 - - [19/Oct/2019 14:12:01] "POST /poll-process HTTP/1.1" 500 -
Traceback (most recent call last):
File "/home/valentyn/.local/lib/python3.6/site-packages/flask/app.py", line 2463, in __call__
return self.wsgi_app(environ, start_response)
File "/home/valentyn/.local/lib/python3.6/site-packages/flask/app.py", line 2449, in wsgi_app
response = self.handle_exception(e)
File "/home/valentyn/.local/lib/python3.6/site-packages/flask/app.py", line 1866, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/valentyn/.local/lib/python3.6/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/home/valentyn/.local/lib/python3.6/site-packages/flask/app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "/home/valentyn/.local/lib/python3.6/site-packages/flask/app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/valentyn/.local/lib/python3.6/site-packages/flask/app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/valentyn/.local/lib/python3.6/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/home/valentyn/.local/lib/python3.6/site-packages/flask/app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "/home/valentyn/.local/lib/python3.6/site-packages/flask/app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/valentyn/Dev/simple_python_web_app/flaskapp/routes.py", line 81, in process
(sel1,)
File "/usr/lib/python3.6/sqlite3/dbapi2.py", line 67, in convert_timestamp
datepart, timepart = val.split(b" ")
ValueError: not enough values to unpack (expected 2, got 1)
127.0.0.1 - - [19/Oct/2019 14:12:02] "GET /poll-process?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
127.0.0.1 - - [19/Oct/2019 14:12:02] "GET /poll-process?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
127.0.0.1 - - [19/Oct/2019 14:12:02] "GET /poll-process?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
127.0.0.1 - - [19/Oct/2019 14:12:03] "GET /poll-process?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
127.0.0.1 - - [19/Oct/2019 14:12:03] "GET /poll-process?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
我可以在Web Developer Network中看到我的表单返回了这样的表单数据:
sel m
submit apply
SQL请求SELECT * FROM poll WHERE sex = 'm';
也可以在我的表的sqlitebrowser中正常工作。
不幸的是,一切都只能单独进行。感谢您的帮助!