Skip to content
Snippets Groups Projects
Commit 7a779c0e authored by robban64's avatar robban64
Browse files

add: args in main and secret-webconfig file

parent d653bfb0
No related branches found
No related tags found
No related merge requests found
import json
from flask import Flask, redirect, request from flask import Flask, redirect, request
from flask_uploads import configure_uploads from flask_uploads import configure_uploads
from flask_uploads.extensions import IMAGES from flask_uploads.extensions import IMAGES
...@@ -8,15 +10,49 @@ from app.apis import init_api ...@@ -8,15 +10,49 @@ from app.apis import init_api
from app.core import bcrypt, db, jwt, ma from app.core import bcrypt, db, jwt, ma
def create_app(config_name="configmodule.DevelopmentConfig"): def load_secret_config(mode, database):
with open("./secret-webconfig.json") as f:
config = json.load(f)
mode_config = config[mode]
result = {"JWT_SECRET_KEY": mode_config["JWT_SECRET_KEY"]}
if database == "postgre":
pg = mode_config["postgre"]
uri = f"postgresql://{pg['USER']}:{pg['PASSWORD']}@{pg['HOST']}:{str(pg['PORT'])}/{pg['DATABASE']}"
result["SQLALCHEMY_DATABASE_URI"] = uri
elif database == "lite":
lite = mode_config["lite"]
result["SQLALCHEMY_DATABASE_URI"] = lite["SQLALCHEMY_DATABASE_URI"]
return result
def create_app(mode, database):
""" """
Creates Flask app, returns it and a SocketIO instance. Call run on the Creates Flask app, returns it and a SocketIO instance. Call run on the
SocketIO instance and pass in the Flask app to start the server. SocketIO instance and pass in the Flask app to start the server.
""" """
if mode == "dev":
config_name = "configmodule.DevelopmentConfig"
elif mode == "prod":
config_name = "configmodule.ProductionConfig"
elif mode == "test":
config_name = "configmodule.TestingConfig"
else:
raise Exception("Invalid mode\nValid modes are: dev, prod and test")
# Init flask # Init flask
app = Flask(__name__, static_url_path="/static", static_folder="static") app = Flask(__name__, static_url_path="/static", static_folder="static")
# Init config
app.config.from_object(config_name) app.config.from_object(config_name)
# Init secret config
secret_config = load_secret_config(mode, database)
app.config.update(secret_config)
print(app.config.get("SERVER_NAME"))
app.url_map.strict_slashes = False app.url_map.strict_slashes = False
with app.app_context(): with app.app_context():
......
...@@ -2,32 +2,6 @@ import os ...@@ -2,32 +2,6 @@ import os
from datetime import timedelta from datetime import timedelta
class DevDbConfig:
HOST = "localhost"
PORT = 5432
USER = "postgres"
PASSWORD = "password"
DATABASE = "teknik8"
SQLALCHEMY_DATABASE_URI = "postgresql://" + USER + ":" + PASSWORD + "@" + HOST + ":" + str(PORT) + "/" + DATABASE
class TestDbConfig:
HOST = "localhost"
PORT = 5432
USER = "postgres"
PASSWORD = "password"
DATABASE = "teknik8-test"
SQLALCHEMY_DATABASE_URI = "postgresql://" + USER + ":" + PASSWORD + "@" + HOST + ":" + str(PORT) + "/" + DATABASE
class LiteDevDbConfig:
SQLALCHEMY_DATABASE_URI = "sqlite:///database.db"
class LiteTestDbConfig:
SQLALCHEMY_DATABASE_URI = "sqlite:///test.db"
class Config: class Config:
DEBUG = False DEBUG = False
TESTING = False TESTING = False
...@@ -55,16 +29,19 @@ class Config: ...@@ -55,16 +29,19 @@ class Config:
OPENAPI_SWAGGER_UI_URL = "https://cdn.jsdelivr.net/npm/swagger-ui-dist/" OPENAPI_SWAGGER_UI_URL = "https://cdn.jsdelivr.net/npm/swagger-ui-dist/"
class DevelopmentConfig(Config, LiteDevDbConfig): class DevelopmentConfig(Config):
DEBUG = True DEBUG = True
SERVER_NAME = "localhost:5000"
class TestingConfig(Config, LiteTestDbConfig): class TestingConfig(Config):
TESTING = True TESTING = True
SERVER_NAME = "localhost:5000"
USER_LOGIN_LOCKED_ATTEMPTS = 4 USER_LOGIN_LOCKED_ATTEMPTS = 4
USER_LOGIN_LOCKED_EXPIRES = timedelta(seconds=4) USER_LOGIN_LOCKED_EXPIRES = timedelta(seconds=4)
class ProductionConfig(Config, LiteDevDbConfig): class ProductionConfig(Config):
DEBUG = False DEBUG = False
TESTING = False TESTING = False
SERVER_NAME = "130.237.227.40:5000" # teknikattan.sys.kth.se
import sys
from app import create_app from app import create_app
"""
Action-arg1: server(default), populate
Mode-arg2: dev(default), prod, test
Database-arg3: lite(default), postgre
"""
if __name__ == "__main__": if __name__ == "__main__":
app, sio = create_app("configmodule.DevelopmentConfig") argv = sys.argv
sio.run(app, port=5000)
# action = argv[1] if len(argv) > 1 else "server"
mode = argv[1] if len(argv) > 1 else "dev"
# database = argv[3] if len(argv) > 3 else "lite"
# if mode == "prod":
# database = "postgre"
if mode == "dev" or mode == "test":
database = argv[2] if len(argv) > 2 else "lite"
elif mode == "prod":
database = "postgre"
else:
print("Invalid args")
print("Dev args: no args, 'dev lite' or 'dev postgre'")
print("Prod args: 'prod'\n")
sys.exit(-1)
print(f"Starting server in {mode} mode with database {database}...")
app, sio = create_app(mode, database)
sio.run(app)
...@@ -3,6 +3,7 @@ This file will reset and polulate the database with some data. ...@@ -3,6 +3,7 @@ This file will reset and polulate the database with some data.
""" """
import random import random
import sys
import app.database.controller as dbc import app.database.controller as dbc
from app import create_app, db from app import create_app, db
...@@ -102,7 +103,7 @@ def create_default_items(): ...@@ -102,7 +103,7 @@ def create_default_items():
) )
for k in range(3): for k in range(3):
dbc.add.question_alternative(f"Alternative {k}", f"Correct {k}", item_question.id) dbc.add.question_alternative(item_question.id, alternative=f"Alternative {k}", correct=f"Correct {k}")
# Add text components # Add text components
# TODO: Add images as components # TODO: Add images as components
...@@ -144,10 +145,27 @@ def create_default_items(): ...@@ -144,10 +145,27 @@ def create_default_items():
if __name__ == "__main__": if __name__ == "__main__":
app, _ = create_app("configmodule.DevelopmentConfig") argv = sys.argv
mode = argv[1] if len(argv) > 1 else "dev"
if mode == "dev" or mode == "test":
database = argv[2] if len(argv) > 2 else "lite"
elif mode == "prod":
database = "postgre"
else:
print("Invalid args")
print("Dev args: no args, 'dev lite' or 'dev postgre'")
print("Prod args: 'prod'\n")
sys.exit(-1)
print(f"Populating server in {mode} mode with database {database}...")
app, _ = create_app(mode, database)
with app.app_context(): with app.app_context():
db.drop_all() db.drop_all()
db.create_all() db.create_all()
create_default_items() create_default_items()
print("Task populating done")
{
"prod":{
"JWT_SECRET_KEY": "super-secret",
"postgre": {
"HOST" : "localhost",
"PORT" : 5432,
"USER" : "postgres",
"PASSWORD" : "password",
"DATABASE" : "teknik8"
}
},
"dev":{
"JWT_SECRET_KEY": "super-secret",
"postgre": {
"HOST" : "localhost",
"PORT" : 5432,
"USER" : "postgres",
"PASSWORD" : "password",
"DATABASE" : "teknik8-dev"
},
"lite":{
"SQLALCHEMY_DATABASE_URI":"sqlite:///database.db"
}
},
"test":{
"JWT_SECRET_KEY": "super-secret",
"postgre": {
"HOST" : "localhost",
"PORT" : 5432,
"USER" : "postgres",
"PASSWORD" : "password",
"DATABASE" : "teknik8-test"
},
"lite":{
"SQLALCHEMY_DATABASE_URI":"sqlite:///test.db"
}
}
}
\ No newline at end of file
...@@ -6,7 +6,7 @@ DISABLE_TESTS = False ...@@ -6,7 +6,7 @@ DISABLE_TESTS = False
@pytest.fixture @pytest.fixture
def app(): def app():
app, _ = create_app("configmodule.TestingConfig") app, _ = create_app("test","lite")
app.app_context().push() app.app_context().push()
db.drop_all() db.drop_all()
db.create_all() db.create_all()
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment