parent
a75ec255ef
commit
7ade5e9b17
Before Width: | Height: | Size: 32 KiB After Width: | Height: | Size: 32 KiB |
@ -1,75 +0,0 @@
|
||||
from flask import Flask, request, make_response, Response, render_template, redirect, url_for, send_from_directory, jsonify, session, flash
|
||||
import pandas as pd
|
||||
import os
|
||||
import uuid
|
||||
|
||||
|
||||
app = Flask(__name__, template_folder='templates', static_folder='static', static_url_path='/')
|
||||
app.secret_key = 'SOME KEY'
|
||||
|
||||
|
||||
@app.route('/', methods=['GET', 'POST'])
|
||||
def index():
|
||||
return render_template('index.html')
|
||||
|
||||
|
||||
@app.route('/set_data')
|
||||
def set_data():
|
||||
session['name'] = 'Session1'
|
||||
session['other'] = 'HelloWorld'
|
||||
return render_template('index.html', message='Session data set.')
|
||||
|
||||
|
||||
@app.route('/get_data')
|
||||
def get_data():
|
||||
if 'name' in session.keys() and 'other' in session.keys():
|
||||
name = session['name']
|
||||
other = session['other']
|
||||
return render_template('index.html', message=f'Name: {name} Content: {other}.')
|
||||
else:
|
||||
return render_template('index.html', message='Session has no data set.')
|
||||
|
||||
|
||||
@app.route('/clear_session')
|
||||
def clear_session():
|
||||
session.clear()
|
||||
return render_template('index.html', message='Session has been cleared')
|
||||
|
||||
|
||||
@app.route('/set_cookie')
|
||||
def set_cookie():
|
||||
response = make_response(render_template('index.html', message='Cookie Set'))
|
||||
response.set_cookie('cookie_name', 'cookie_value')
|
||||
return response
|
||||
|
||||
|
||||
@app.route('/get_cookie')
|
||||
def get_cookie():
|
||||
cookie_value = request.cookies['cookie_name']
|
||||
return render_template('index.html', message=f'Cookie value: {cookie_value}')
|
||||
|
||||
|
||||
@app.route('/remove_cookie')
|
||||
def remove_cookie():
|
||||
response = make_response(render_template('index.html', message='Cookie removed'))
|
||||
response.set_cookie('cookie_name', expires=0)
|
||||
return response
|
||||
|
||||
|
||||
@app.route('/login', methods=['GET', 'POST'])
|
||||
def login():
|
||||
if request.method == 'GET':
|
||||
return render_template('login.html')
|
||||
elif request.method == 'POST':
|
||||
username = request.form.get('username')
|
||||
password = request.form.get('password')
|
||||
if username == 'kynsight' and password == 'pass':
|
||||
flash('Successfull Login!')
|
||||
return render_template('index.html', message="")
|
||||
else:
|
||||
flash('Login Failed!')
|
||||
return render_template('index.html', message="")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(host='0.0.0.0', port=5000, debug=True)
|
@ -0,0 +1,37 @@
|
||||
from flask import Flask, redirect, url_for
|
||||
from flask_login import LoginManager
|
||||
from flask_bcrypt import Bcrypt
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_migrate import Migrate
|
||||
|
||||
db = SQLAlchemy()
|
||||
|
||||
|
||||
def create_app():
|
||||
app = Flask(__name__, template_folder='templates', static_folder='static', static_url_path='/')
|
||||
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///./test.db'
|
||||
app.secret_key = 'SOME KEY'
|
||||
db.init_app(app)
|
||||
|
||||
login_manager = LoginManager()
|
||||
login_manager.init_app(app)
|
||||
|
||||
from models import User
|
||||
|
||||
@login_manager.user_loader
|
||||
def load_user(uid):
|
||||
return User.query.get(uid)
|
||||
|
||||
@login_manager.unauthorized_handler
|
||||
def unauthorized_callback():
|
||||
return redirect(url_for('index'))
|
||||
|
||||
|
||||
bcrypt = Bcrypt(app)
|
||||
|
||||
|
||||
from routes import register_routes
|
||||
register_routes(app, db, bcrypt)
|
||||
Migrate(app, db)
|
||||
return app
|
||||
|
Binary file not shown.
@ -0,0 +1 @@
|
||||
Single-database configuration for Flask.
|
Binary file not shown.
@ -0,0 +1,50 @@
|
||||
# A generic, single database configuration.
|
||||
|
||||
[alembic]
|
||||
# template used to generate migration files
|
||||
# file_template = %%(rev)s_%%(slug)s
|
||||
|
||||
# set to 'true' to run the environment during
|
||||
# the 'revision' command, regardless of autogenerate
|
||||
# revision_environment = false
|
||||
|
||||
|
||||
# Logging configuration
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic,flask_migrate
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARN
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[logger_flask_migrate]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = flask_migrate
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
@ -0,0 +1,113 @@
|
||||
import logging
|
||||
from logging.config import fileConfig
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from alembic import context
|
||||
|
||||
# this is the Alembic Config object, which provides
|
||||
# access to the values within the .ini file in use.
|
||||
config = context.config
|
||||
|
||||
# Interpret the config file for Python logging.
|
||||
# This line sets up loggers basically.
|
||||
fileConfig(config.config_file_name)
|
||||
logger = logging.getLogger('alembic.env')
|
||||
|
||||
|
||||
def get_engine():
|
||||
try:
|
||||
# this works with Flask-SQLAlchemy<3 and Alchemical
|
||||
return current_app.extensions['migrate'].db.get_engine()
|
||||
except (TypeError, AttributeError):
|
||||
# this works with Flask-SQLAlchemy>=3
|
||||
return current_app.extensions['migrate'].db.engine
|
||||
|
||||
|
||||
def get_engine_url():
|
||||
try:
|
||||
return get_engine().url.render_as_string(hide_password=False).replace(
|
||||
'%', '%%')
|
||||
except AttributeError:
|
||||
return str(get_engine().url).replace('%', '%%')
|
||||
|
||||
|
||||
# add your model's MetaData object here
|
||||
# for 'autogenerate' support
|
||||
# from myapp import mymodel
|
||||
# target_metadata = mymodel.Base.metadata
|
||||
config.set_main_option('sqlalchemy.url', get_engine_url())
|
||||
target_db = current_app.extensions['migrate'].db
|
||||
|
||||
# other values from the config, defined by the needs of env.py,
|
||||
# can be acquired:
|
||||
# my_important_option = config.get_main_option("my_important_option")
|
||||
# ... etc.
|
||||
|
||||
|
||||
def get_metadata():
|
||||
if hasattr(target_db, 'metadatas'):
|
||||
return target_db.metadatas[None]
|
||||
return target_db.metadata
|
||||
|
||||
|
||||
def run_migrations_offline():
|
||||
"""Run migrations in 'offline' mode.
|
||||
|
||||
This configures the context with just a URL
|
||||
and not an Engine, though an Engine is acceptable
|
||||
here as well. By skipping the Engine creation
|
||||
we don't even need a DBAPI to be available.
|
||||
|
||||
Calls to context.execute() here emit the given string to the
|
||||
script output.
|
||||
|
||||
"""
|
||||
url = config.get_main_option("sqlalchemy.url")
|
||||
context.configure(
|
||||
url=url, target_metadata=get_metadata(), literal_binds=True
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online():
|
||||
"""Run migrations in 'online' mode.
|
||||
|
||||
In this scenario we need to create an Engine
|
||||
and associate a connection with the context.
|
||||
|
||||
"""
|
||||
|
||||
# this callback is used to prevent an auto-migration from being generated
|
||||
# when there are no changes to the schema
|
||||
# reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
|
||||
def process_revision_directives(context, revision, directives):
|
||||
if getattr(config.cmd_opts, 'autogenerate', False):
|
||||
script = directives[0]
|
||||
if script.upgrade_ops.is_empty():
|
||||
directives[:] = []
|
||||
logger.info('No changes in schema detected.')
|
||||
|
||||
conf_args = current_app.extensions['migrate'].configure_args
|
||||
if conf_args.get("process_revision_directives") is None:
|
||||
conf_args["process_revision_directives"] = process_revision_directives
|
||||
|
||||
connectable = get_engine()
|
||||
|
||||
with connectable.connect() as connection:
|
||||
context.configure(
|
||||
connection=connection,
|
||||
target_metadata=get_metadata(),
|
||||
**conf_args
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
@ -0,0 +1,24 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = ${repr(up_revision)}
|
||||
down_revision = ${repr(down_revision)}
|
||||
branch_labels = ${repr(branch_labels)}
|
||||
depends_on = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade():
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade():
|
||||
${downgrades if downgrades else "pass"}
|
@ -0,0 +1,35 @@
|
||||
"""empty message
|
||||
|
||||
Revision ID: 0b1a6cc67556
|
||||
Revises:
|
||||
Create Date: 2024-06-28 08:57:09.270357
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '0b1a6cc67556'
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table('users',
|
||||
sa.Column('uid', sa.Integer(), nullable=False),
|
||||
sa.Column('username', sa.String(), nullable=False),
|
||||
sa.Column('password', sa.String(), nullable=False),
|
||||
sa.Column('role', sa.String(), nullable=True),
|
||||
sa.Column('description', sa.String(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('uid')
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_table('users')
|
||||
# ### end Alembic commands ###
|
Binary file not shown.
@ -0,0 +1,18 @@
|
||||
from app import db
|
||||
from flask_login import UserMixin
|
||||
|
||||
|
||||
class User(db.Model, UserMixin):
|
||||
__tablename__ = 'users'
|
||||
|
||||
uid = db.Column(db.Integer, primary_key=True)
|
||||
username = db.Column(db.String, nullable=False)
|
||||
password = db.Column(db.String, nullable=False)
|
||||
role = db.Column(db.String, nullable=True)
|
||||
description = db.Column(db.String, nullable=True)
|
||||
|
||||
def __repr__(self):
|
||||
return f'<User:{self.username}, {self.role}>'
|
||||
|
||||
def get_id(self):
|
||||
return self.uid
|
@ -0,0 +1,52 @@
|
||||
from flask import Flask, render_template, request, redirect, url_for
|
||||
from models import User
|
||||
from flask_login import login_user, logout_user, current_user, login_required
|
||||
|
||||
def register_routes(app, db, brcypt):
|
||||
@app.route('/', methods=['GET','POST'])
|
||||
def index():
|
||||
return render_template('index.html')
|
||||
|
||||
@app.route('/signup', methods = ['GET','POST'])
|
||||
def signup():
|
||||
if request.method == 'GET':
|
||||
return render_template('signup.html')
|
||||
elif request.method == 'POST':
|
||||
username = request.form.get('username')
|
||||
password = request.form.get('password')
|
||||
|
||||
hashed_pass = brcypt.generate_password_hash(password)
|
||||
user = User(username=username, password=hashed_pass)
|
||||
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
return redirect(url_for('index'))
|
||||
|
||||
|
||||
@app.route('/login', methods = ['GET','POST'])
|
||||
def login():
|
||||
if request.method == 'GET':
|
||||
return render_template('login.html')
|
||||
elif request.method == 'POST':
|
||||
username = request.form.get('username')
|
||||
password = request.form.get('password')
|
||||
|
||||
user = User.query.filter(User.username == username).first()
|
||||
|
||||
if brcypt.check_password_hash(user.password, password):
|
||||
login_user(user)
|
||||
return redirect(url_for('index'))
|
||||
else:
|
||||
return f"failed"
|
||||
|
||||
@app.route('/logout')
|
||||
def logout():
|
||||
logout_user()
|
||||
return redirect(url_for('index'))
|
||||
|
||||
@app.route('/secret')
|
||||
@login_required
|
||||
def secret():
|
||||
return "my SercreT"
|
||||
|
||||
|
@ -0,0 +1,6 @@
|
||||
from app import create_app
|
||||
|
||||
flask_app = create_app()
|
||||
|
||||
if __name__ == '__main__':
|
||||
flask_app.run(host='0.0.0.0', debug='Ture')
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue