Reputation: 19
Testing out an apps.py in my environment project directory, this is my script for a login/register form:
#app.py
from flask import Flask, request, session, redirect, url_for, render_template, flash
from django.apps import AppConfig
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import psycopg2 #pip install psycopg2
import psycopg2.extras
import re
from werkzeug.security import generate_password_hash, check_password_hash
#
class IndexConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'index'
#
app = Flask(__name__)
app.secret_key = 'cairocoders-ednalan'
DB_HOST = "localhost"
DB_NAME = "users"
DB_USER = "postgres"
DB_PASS = "admin"
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)
@app.route('/')
def home():
# Check if user is loggedin
if 'loggedin' in session:
# User is loggedin show them the home page
return render_template('home.html', username=session['username'])
# User is not loggedin redirect to login page
return redirect(url_for('login'))
@app.route('/login/', methods=['GET', 'POST'])
def login():
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
# Check if "username" and "password" POST requests exist (user submitted form)
if request.method == 'POST' and 'username' in request.form and 'password' in request.form:
username = request.form['username']
password = request.form['password']
print(password)
# Check if account exists using MySQL
cursor.execute('SELECT * FROM users WHERE username = %s', (username,))
# Fetch one record and return result
account = cursor.fetchone()
if account:
password_rs = account['password']
print(password_rs)
# If account exists in users table in out database
if check_password_hash(password_rs, password):
# Create session data, we can access this data in other routes
session['loggedin'] = True
session['id'] = account['id']
session['username'] = account['username']
# Redirect to home page
return redirect(url_for('home'))
else:
# Account doesnt exist or username/password incorrect
flash('Incorrect username/password')
else:
# Account doesnt exist or username/password incorrect
flash('Incorrect username/password')
return render_template('login.html')
@app.route('/register', methods=['GET', 'POST'])
def register():
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
# Check if "username", "password" and "email" POST requests exist (user submitted form)
if request.method == 'POST' and 'username' in request.form and 'password' in request.form and 'email' in request.form:
# Create variables for easy access
fullname = request.form['fullname']
username = request.form['username']
password = request.form['password']
email = request.form['email']
_hashed_password = generate_password_hash(password)
#Check if account exists using MySQL
cursor.execute('SELECT * FROM users WHERE username = %s', (username,))
account = cursor.fetchone()
print(account)
# If account exists show error and validation checks
if account:
flash('Account already exists!')
elif not re.match(r'[^@]+@[^@]+\.[^@]+', email):
flash('Invalid email address!')
elif not re.match(r'[A-Za-z0-9]+', username):
flash('Username must contain only characters and numbers!')
elif not username or not password or not email:
flash('Please fill out the form!')
else:
# Account doesnt exists and the form data is valid, now insert new account into users table
cursor.execute("INSERT INTO users (fullname, username, password, email) VALUES (%s,%s,%s,%s)", (fullname, username, _hashed_password, email))
conn.commit()
flash('You have successfully registered!')
elif request.method == 'POST':
# Form is empty... (no POST data)
flash('Please fill out the form!')
# Show registration form with message (if any)
return render_template('register.html')
@app.route('/logout')
def logout():
# Remove session data, this will log the user out
session.pop('loggedin', None)
session.pop('id', None)
session.pop('username', None)
# Redirect to login page
return redirect(url_for('login'))
@app.route('/profile')
def profile():
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
# Check if user is loggedin
if 'loggedin' in session:
cursor.execute('SELECT * FROM users WHERE id = %s', [session['id']])
account = cursor.fetchone()
# Show the profile page with account info
return render_template('profile.html', account=account)
# User is not loggedin redirect to login page
return redirect(url_for('login'))
if __name__ == "__main__":
app.run(debug=True)
This is the error I receive when I run 'flask run' in the terminal, not sure what it means at all.
What I'm trying to achieve is connecting psql database to my website and using flask as the web framework
PS C:\Users\sefni\Documents\test_django_app\Environments\testProject> flask run
flask : The term 'flask' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ flask run
+ ~~~~~
+ CategoryInfo : ObjectNotFound: (flask:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Upvotes: 1
Views: 3770
Reputation: 1522
You can run the app using app.run() in your case you need to execute python app.py
but If you want it to run using flask run then you need to set the env executing the two commands.
set FLASK_APP=application.py
set FLASK_DEBUG=1
now you can run the app using the below line
flask run
if you are using bash then use export
in place of set
. here for reference
Upvotes: 2
Reputation: 6027
Either you have not installed flask
. You should do:
pip install flask
Or you are not running the application correctly. You run like this (from the directory where your code is):
python -m flask run
Upvotes: 2