34
loading...
This website collects cookies to deliver better user experience
Flask
for in this article.Flask
classMySQL
flask
from which we require the Flask
class and render_template
, and MySQL
from flask_mysqldb
.You need to install the flask
modules and flask_mysqldb
if you do not already have them.
python3 -m pip install flask
python3 -m pip install flask_mysqldb
from flask import Flask, render_template, request
from flask_mysqldb import MySQL
app = Flask(__name__)
__name__
because depending on if it's started as application or imported as a module the name will be different (__main__
vs the actual import name)app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'MyDB'
You need to replace the configurations with yours where necessary.
Flask
instance you can challenge your yourself.MySQL
instance passing app
(or the name you used).mysql = MySQL(app)
routes
.route()
decorator to bind a function to a URL.@app.route('/')
def form():
return render_template('form.html')
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method != "POST":
return "Use the sign up form"
if request.method == 'POST':
details = request.form
name = details['name']
email = details['email']
message = details['message']
cursor = mysql.connection.cursor()
cursor.execute("INSERT INTO users(name, email, message) VALUES (%s, %s, %s)",(name, email, message))
cursor.connection.commit()
cursor.close()
return f'Created user {name}'
form()
function when a user visits the root URL
.form.html
page using the render_template
method we imported from flask
.templates
.<form action="/register" method="POST">
<p>NAME: <input type="text" name="name" /></p>
<p>EMAIL: <input type="text" name="email" /></p>
<p>BIO: <input type="text" name="message" /></p>
<p><input type="submit" value="submit" /></p>
</form>
flask run
command or using python and the -m switch command and flask: python3 -m flask run
.FLASK_APP=app.py
. export FLASK_APP=app.py
flask run
set FLASK_APP=app
flask run
$env:FLASK_APP = "app"
flask run
/register
using the POST
method.Use the sign up form
- to the user.