Files
MermsCoreBackendFlask/services/web/project/__init__.py
T
CHIEFSOFT\ameye 92f09ef70e requst argd
2024-12-15 14:01:32 -05:00

327 lines
12 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import os
import psycopg2
from dotenv import load_dotenv
from functools import wraps
import datetime
import jwt
import random
import json
import psycopg2.extras
import pandas as pd
import project.validate.validate as validate
#import project.models.members as Members
from project.models.members import Members
from flask_cors import CORS
from flasgger import Swagger, swag_from
#from models.models import User
from flask import (
Flask,
jsonify,
send_from_directory,
request,
)
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
#import SQLAlchemy
#from werkzeug.utils import secure_filename
load_dotenv()
app = Flask(__name__)
CORS(app)
app.config.from_object("project.config.Config")
db = SQLAlchemy(app)
#jwt_secret = os.getenv("JWT_SECRET")
app.config['SECRET_KEY'] = os.getenv("JWT_SECRET")
#print( "aaaa-bbbb--ccccc" )
#print( jwt_secret )
template = {
"swagger": "2.0",
"info": {
"title": "MERMS Core API",
"description": "This API was developed using Python Flask, which provides an interface for core MERMS endpoints.",
"version": "1.0"
}
}
app.config['SWAGGER'] = {
'title': 'MERMS API',
'uiversion': 2,
'template': './resources/flasgger/swagger_ui.html'
}
Swagger(app, template=template)
@swag_from('../../docs/consume.yml')
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
#token = request.args.get('token')
token = request.headers["Authorization"].split(" ")[1]
# print(token)
if not token:
return jsonify({'message': 'Error - missing token'}), 403
try:
data= jwt.decode(token, app.config['SECRET_KEY'], algorithms=["HS256"])
except:
return jsonify({'message': 'Token is invalid'}),403
return f(data, *args, **kwargs)
return decorated
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(128), unique=True, nullable=False)
active = db.Column(db.Boolean(), default=True, nullable=False)
def __init__(self, email):
self.email = email
dataUrl = os.getenv("DATABASE_URL")
connection = psycopg2.connect(dataUrl)
#engine = SQLAlchemy.create_engine(dataUrl)
engine = create_engine(dataUrl)
@app.route("/")
def hello_world():
action_data = {
"last_update": datetime.datetime.utcnow(),
"initial": random.randint(0, 10),
"processing": random.randint(0, 10),
"verifying" : random.randint(0, 10),
"completed" : random.randint(0, 10),
"top_bar": [
{"id": "1", "description": "Contacts" , "last_update": "10-10-2010 11:00 AM", "value": '0' , "data_span":'Last 2 months'},
{"id": "2", "description": "Site Traffic" , "last_update": "10-10-2010 11:30 AM", "value": '0', "data_span":'Past 12 hours'},
{"id": "3", "description": "Appointments" , "last_update": "10-12-2010 11:30 AM", "value": '0', "data_span":'Last 14 days'},
{"id": "4", "description": "Purchases" , "last_update": "10-12-2010 11:30 AM", "value": '0', "data_span":'Last 3 months'},
],
"actions": [
{"no": "1", "description": "Welcome to MERMS" , "date": "10-10-2010 11:00 AM", "status": 'completed'},
{"no": "2", "description": "Personal Blog Setup" , "date": "10-10-2010 11:30 AM", "status": 'processing'},
{"no": "3", "description": "Web Traffic Analysis" , "date": "10-12-2010 11:30 AM", "status": 'verifying'},
]
}
GLOBAL_AVG = """SELECT * FROM members WHERE id > 0;"""
result = pd.read_sql(GLOBAL_AVG, engine)
print(result)
cols = result.columns.difference(['Col1'])
d = (result.groupby('Col1')[cols]
.apply(lambda x: x.to_dict('r'))
.reset_index(name='Other_details')
.to_json(orient='records'))
#json_data = [json.loads(row[0]) for row in result]
with connection:
with connection.cursor(cursor_factory=psycopg2.extras.DictCursor) as cursor:
cursor.execute(GLOBAL_AVG)
account = cursor.fetchall()
print(account[0]["uid"])
# for row in account.rows:
# print(row['id'], row['uid'])
# print(account)
# # Convert the list of tuples to a list of JSON objects
# json_data = [json.loads(row[0]) for row in account]
# #print(account)
# json_data = json.dumps(account)
# print(json_data)
# connection.close()
return jsonify(result=account, action_data=action_data, account=account)
GLOBAL_AVG = """SELECT * FROM members WHERE id = 1;"""
with connection:
with connection.cursor() as cursor:
cursor.execute(GLOBAL_AVG)
account = cursor.fetchone()
return jsonify(hello="ameye world")
# return {"account": account}
@app.route("/panel/auth/login", methods=["POST"])
def start_login():
try:
data = request.json
if not data:
return {
"message": "Please provide user details",
"data": None,
"error": "Bad request"
}, 400
# validate input
is_validated = validate.validate_username_and_password(data.get('username'), data.get('password'))
if is_validated is not True:
return dict(message='Invalid data', data=None, error=is_validated), 400
member = Members().login(
data["username"],
data["password"]
)
if member:
try:
user = {}
user_data = {}
user_data["id"] = member[0]
user_data["uid"] = member[1]
# token should expire after 24 hrs
user["token"] = jwt.encode(
{"user": user_data, 'exp' : datetime.datetime.utcnow() + datetime.timedelta(minutes=30)},
app.config["SECRET_KEY"],
algorithm="HS256"
)
return {
"message": "Successfully fetched auth token",
"data": user
}
except Exception as e:
return {
"error": "Something went wrong",
"message": str(e)
}, 500
return {
"message": "Error fetching auth token!, invalid email or password",
"data": None,
"error": "Unauthorized"
}, 404
except Exception as e:
return {
"message": "Something went wrong!",
"error": str(e),
"data": None
}, 500
@app.route("/panel/auth/register")
def start_register():
return jsonify(hello="ameye world")
@app.route("/panel/auth/reset")
def start_resetpass():
return jsonify(hello="ameye world")
@app.route("/panel/account")
@token_required
def panel_account(current_user):
# print(current_user["user"]["uid"])
user_uid = current_user["user"]["uid"]
# print(user_uid)
member_dash = Members().get_member_by_uid(user_uid)
print(member_dash[0])
print(member_dash[0][0])
return jsonify(hello=current_user)
@app.route("/panel/account/dash")
@token_required
def dashboard(current_user):
dash_data = {
"username": "sanyaameye",
"account_name": "This is the test account name",
"firstname": "TestFirstname",
"lastname" : "Testlastname",
"email": "bestemail@email.com"
}
return jsonify(dash_data=dash_data)
@app.route("/panel/account/products")
@token_required
def panel_products(current_user):
products_data = {
"last_update": datetime.datetime.utcnow(),
"products": [
{"uid":"A0001","icon": "icon_product", "description": "Professional Website" , "status": 'Activate now'},
{"uid":"B0001","icon": "icon_product", "description": "Professional Blog" , "status": 'Activate now'},
{"uid":"C0002","icon": "icon_product", "description": "Business Website" , "status": 'Activate now'},
{"uid":"D0001","icon": "icon_product", "description": "Business Blog Site" , "status": 'Activate now'},
{"uid":"E0001","icon": "icon_product", "description": "OpenEmr" , "status": 'Activate now'},
{"uid":"F0001","icon": "icon_product", "description": "Dummy Dummy" , "status": 'Activate now'},
]
}
return jsonify(products_data=products_data)
@app.route("/panel/account/actions")
@token_required
def recent_actions(current_user):
action_data = {
"last_update": datetime.datetime.utcnow(),
"initial": random.randint(0, 10),
"processing": random.randint(0, 10),
"verifying" : random.randint(0, 10),
"completed" : random.randint(0, 10),
"top_bar": [
{"id": "1", "description": "Contacts" , "last_update": "10-10-2010 11:00 AM", "value": '0' , "data_span":'Last 2 months'},
{"id": "2", "description": "Site Traffic" , "last_update": "10-10-2010 11:30 AM", "value": '0', "data_span":'Past 12 hours'},
{"id": "3", "description": "Appointments" , "last_update": "10-12-2010 11:30 AM", "value": '0', "data_span":'Last 14 days'},
{"id": "4", "description": "Purchases" , "last_update": "10-12-2010 11:30 AM", "value": '0', "data_span":'Last 3 months'},
],
"actions": [
{"no": "1", "description": "Welcome to MERMS" , "date": "10-10-2010 11:00 AM", "status": 'completed'},
{"no": "2", "description": "Personal Blog Setup" , "date": "10-10-2010 11:30 AM", "status": 'processing'},
{"no": "3", "description": "Web Traffic Analysis" , "date": "10-12-2010 11:30 AM", "status": 'verifying'},
]
}
return jsonify(action_data=action_data)
@app.route("/panel/account/products/url")
@token_required
def product_urls(current_user):
url_data = {
"last_update": datetime.datetime.utcnow(),
"url": [
{"no": "1", "description": "Main Website", "url":'https://starter.0ach30996.mermsemr.com', "date": "10-10-2010 11:00 AM", "status": 'Active'},
{"no": "1", "description": "Personal Blog", "url":'https://starterblo.0ach30996.mermsemr.com', "date": "10-10-2010 11:00 AM", "status": 'Updating'},
{"no": "1", "description": "Business Web", "url":'https://starterbus.0ach30996.mermsemr.com', "date": "10-10-2010 11:00 AM", "status": 'Active'},
{"no": "1", "description": "Business Blog", "url":'https://starterbblog.0ach30996.mermsemr.com', "date": "10-10-2010 11:00 AM", "status": 'Active'},
]
}
return jsonify(url_data=url_data)
@app.route("/panel/account/payments")
@token_required
def account_payments(current_user):
payments = {
"last_update": datetime.datetime.utcnow(),
"url": [
{"no": "1", "description": "Welcome to MERMS" , "date": "10-10-2010 11:00 AM", "status": 'completed'},
{"no": "2", "description": "Personal Blog Setup" , "date": "10-10-2010 11:30 AM", "status": 'processing'},
{"no": "3", "description": "Web Traffic Analysis" , "date": "10-12-2010 11:30 AM", "status": 'verifying'},
]
}
return jsonify(payments_data=payments_data)
##. Description Date Status "10-10-2021 10 AM"
@app.route("/panel/myproduct/dash")
@token_required
def myproduct(current_user):
# data = request.json
# print(data)
product_id = request.args
print(product_id)
myproduct_data = {
"myproduct_uid":"",
"banner": "p4.jpg",
"description": "Commitment is something that comes from understanding that everything has its price and then having the willingness to pay that price. This is important because nobody wants to put significant effort into something, only to find out after the fact that the price was too high.The price is something not necessarily defined as financial. It could be time, effort, sacrifice, money or perhaps, something else.",
"title": "Open EMR",
"subscription_text" : "Start with your goals in mind and then work possible.ith yand Goals. If the plan doesnt support the vision then change it!",
"promotion_text": "FAQ pages is for consistency"
}
return jsonify(myproduct_data=myproduct_data)