I'm trying to get started using Flask with PostgreSQL to create a simple project. For the sake of completeness I will include all terminal commands along with my code. Working in my SQL_Example folder and a local PostgreSQL database "lecture3" with table "flights":
$ python3 -m venv venv
$ . venv/bin/activate
$ pip install Flask
Now I continued with the following code:
import os
from flask import Flask, render_template, request
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
app = Flask(__name__)
engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))
@app.route("/")
def index():
flights = db.execute("SELECT * FROM flights").fetchall()
return render_template("index.html", flights=flights)
@app.route("/book", methods=["POST"])
def book():
name = request.form.get("name")
try:
flight_id = int(request.form.get("flight_id"))
except ValueError:
return render_template("error.html", message="Invalid flight number.")
if db.execute("SELECT * FROM flights WHERE id = :id", {"id": flight_id}).rowcount == 0:
return render_template("error.html", message="No such flight with that id.")
db.execute("INSERT INTO passengers (name, flight_id) VALUES (:name, :flight_id)", {"name": name, "flight_id": flight_id})
db.commit()
return render_template("success.html")
Executing the following commands:
$ export FLASK_APP="application.py"
$ flask run
Encountered the following error:
Traceback (most recent call last):
File "/Users/spencermiller/Desktop/SQL_Example/venv/bin/flask", line 11, in <module>
sys.exit(main())
File "/Users/spencermiller/Desktop/SQL_Example/venv/lib/python3.7/site-packages/flask/cli.py", line 967, in main
cli.main(args=sys.argv[1:], prog_name="python -m flask" if as_module else None)
File "/Users/spencermiller/Desktop/SQL_Example/venv/lib/python3.7/site-packages/flask/cli.py", line 586, in main
return super(FlaskGroup, self).main(*args, **kwargs)
File "/Users/spencermiller/Desktop/SQL_Example/venv/lib/python3.7/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/Users/spencermiller/Desktop/SQL_Example/venv/lib/python3.7/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/Users/spencermiller/Desktop/SQL_Example/venv/lib/python3.7/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/Users/spencermiller/Desktop/SQL_Example/venv/lib/python3.7/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/Users/spencermiller/Desktop/SQL_Example/venv/lib/python3.7/site-packages/click/decorators.py", line 73, in new_func
return ctx.invoke(f, obj, *args, **kwargs)
File "/Users/spencermiller/Desktop/SQL_Example/venv/lib/python3.7/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/Users/spencermiller/Desktop/SQL_Example/venv/lib/python3.7/site-packages/flask/cli.py", line 848, in run_command
app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)
File "/Users/spencermiller/Desktop/SQL_Example/venv/lib/python3.7/site-packages/flask/cli.py", line 305, in __init__
self._load_unlocked()
File "/Users/spencermiller/Desktop/SQL_Example/venv/lib/python3.7/site-packages/flask/cli.py", line 330, in _load_unlocked
self._app = rv = self.loader()
File "/Users/spencermiller/Desktop/SQL_Example/venv/lib/python3.7/site-packages/flask/cli.py", line 388, in load_app
app = locate_app(self, import_name, name)
File "/Users/spencermiller/Desktop/SQL_Example/venv/lib/python3.7/site-packages/flask/cli.py", line 240, in locate_app
__import__(module_name)
File "/Users/spencermiller/Desktop/SQL_Example/application.py", line 9, in <module>
engine = create_engine(os.getenv("DATABASE_URL"))
File "/Users/spencermiller/Desktop/SQL_Example/venv/lib/python3.7/site-packages/sqlalchemy/engine/__init__.py", line 479, in create_engine
return strategy.create(*args, **kwargs)
File "/Users/spencermiller/Desktop/SQL_Example/venv/lib/python3.7/site-packages/sqlalchemy/engine/strategies.py", line 56, in create
plugins = u._instantiate_plugins(kwargs)
AttributeError: 'NoneType' object has no attribute '_instantiate_plugins'
I have seen some similar issues but none of those solutions have worked for me.
Environment variable:
TERM_PROGRAM=Apple_Terminal
SHELL=/bin/bash
TERM=xterm-256color
TMPDIR=/var/folders/pf/2_4xxn2s0jl7m8r0xv9wg9fr0000gp/T/
Apple_PubSub_Socket_Render=/private/tmp/com.apple.launchd.CyouqBAyRx/Render
TERM_PROGRAM_VERSION=421.1.1
OLDPWD=/Users/spencermiller
TERM_SESSION_ID=3CA9A778-D58A-405E-8EC3-D5F86D87FFFA
USER=spencermiller
SSH_AUTH_SOCK=/private/tmp/com.apple.launchd.aXcWzrdMYX/Listeners
PATH=/Library/Frameworks/Python.framework/Versions/3.7/bin:/Library/Frameworks/Python.framework/Versions/3.7/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin
PWD=/Users/spencermiller/Desktop/SQL_Example
LANG=en_CA.UTF-8
XPC_FLAGS=0x0
XPC_SERVICE_NAME=0
SHLVL=1
HOME=/Users/spencermiller
LOGNAME=spencermiller
DISPLAY=/private/tmp/com.apple.launchd.WkWoFkNc6W/org.macosforge.xquartz:0
_=/usr/bin/printenv
in this piece of code, you are trying to create your flask's engine with a database URL that is on you environment variables.
engine = create_engine(os.getenv("DATABASE_URL"))
My guess is that you didn't set up this environment variable, so you're trying to create an engine with a None url.
You need to set your env variable, or hard code your DATABASE_URL into python.
db_url = 'postgresql+psycopg2://{user}:{password}@{url}/{db}'
engine = create_engine(db_url)
Hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With