文件组织如下:
代码如下:
#init.py文件
# -- coding: utf-8 --
import os
import sys
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
DIALECT = 'mysql'
DRIVER = 'pymysql'
USERNAME = 'root'
PASSWORD = '12345678'
HOST = '127.0.0.1'
PORT = '3306'
DATABASE = 'sqlaldata'#要先创建这个数据库文件
app = Flask(__name__)
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'dev')
app.config['SQLALCHEMY_DATABASE_URI'] = "{}+{}://{}:{}@{}:{}/{}?charset=utf8".format(DIALECT, DRIVER, USERNAME, PASSWORD, HOST, PORT,DATABASE)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
from database import views,forms,models
#forms.py文件
from flask_wtf import FlaskForm
from wtforms import SubmitField, TextAreaField
from wtforms.validators import DataRequired
class NewNoteForm(FlaskForm):
body = TextAreaField('Body', validators=[DataRequired()])
submit = SubmitField('Save')
#views.py
from flask import redirect, url_for, abort, render_template, flash
from database import app, db
from database.models import Note
from database.forms import NewNoteForm
@app.route('/new', methods=['GET', 'POST'])
def new_note():
form = NewNoteForm()
if form.validate_on_submit():
body = form.body.data
note = Note(body=body)
db.session.add(note)
db.session.commit()
flash('Your note is saved.')
return redirect(url_for('index'))
return render_template('new_note.html', form=form)
#models.py
from database import db
class Note(db.Model):
id = db.Column(db.Integer,primary_key=True)
body = db.Column(db.Text)
程序运行时,在地址栏输入:http://localhost:5000/new,提示Could not build url for endpoint ‘index’. Did you mean ‘new_note’ instead?
而在views.py文件中添加:
@app.route(‘/’)
def index():
pass
则能正确显示页面:
请问index函数起什么作用?