Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create tables automatically even if running via a wsgi server #89

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
4 changes: 2 additions & 2 deletions app/config.py.sample
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ SECRET_KEY = 'random long string with alphanumeric + #()*&'

### Do not change below unless you know what you are doing
UPLOAD_FOLDER = '/tmp'
ALLOWED_EXTENSIONS = {'xlsx'}
ALLOWED_EXTENSIONS = {'xlsx'}

### remote systems can call this program like
### remote systems can call this program like
### /v1/{REMOTE_CALL_API_KEY}/check_one_serial/<serial> and check one serial, returns back json
REMOTE_CALL_API_KEY = 'set_unguessable_remote_api_key_lkjdfljerlj3247LKJ'
42 changes: 21 additions & 21 deletions app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ def allowed_file(filename):

class User(UserMixin):
""" A minimal and singleton user class used only for administrative tasks """

def __init__(self, id):
self.id = id

Expand All @@ -73,13 +74,11 @@ def __repr__(self):
@app.route('/db_status/', methods=['GET'])
@login_required
def db_status():

""" show some status about the DB """


db = get_database_connection()
cur = db.cursor()

# collect some stats for the GUI
try:
cur.execute("SELECT count(*) FROM serials")
Expand Down Expand Up @@ -111,8 +110,9 @@ def db_status():
except:
log_db_check = 'Can not read db_check logs... yet'

return render_template('db_status.html', data={'serials': num_serials, 'invalids': num_invalids,
'log_import': log_import, 'log_db_check': log_db_check, 'log_filename': log_filename})
return render_template('db_status.html', data={'serials': num_serials, 'invalids': num_invalids,
'log_import': log_import, 'log_db_check': log_db_check,
'log_filename': log_filename})


@app.route('/', methods=['GET', 'POST'])
Expand All @@ -132,9 +132,9 @@ def home():
flash('No selected file', 'danger')
return redirect(request.url)
if file and allowed_file(file.filename):
#TODO: is space find in a file name? check if it works
# TODO: is space find in a file name? check if it works
filename = secure_filename(file.filename)
filename.replace(' ', '_') # no space in filenames! because we will call them as command line arguments
filename.replace(' ', '_') # no space in filenames! because we will call them as command line arguments
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(file_path)
subprocess.Popen(["python", "import_db.py", file_path])
Expand All @@ -145,7 +145,6 @@ def home():

cur = db.cursor()


# get last 5000 sms
cur.execute("SELECT * FROM PROCESSED_SMS ORDER BY date DESC LIMIT 5000")
all_smss = cur.fetchall()
Expand All @@ -158,10 +157,10 @@ def home():
try:
cur.execute("SELECT count(*) FROM PROCESSED_SMS WHERE status = 'OK'")
num_ok = cur.fetchone()[0]
except:
except:
num_ok = 'error'

try:
try:
cur.execute("SELECT count(*) FROM PROCESSED_SMS WHERE status = 'FAILURE'")
num_failure = cur.fetchone()[0]
except:
Expand All @@ -182,6 +181,7 @@ def home():
return render_template('index.html', data={'smss': smss, 'ok': num_ok, 'failure': num_failure, 'double': num_double,
'notfound': num_notfound})


@app.route("/login", methods=["GET", "POST"])
@limiter.limit("10 per minute")
def login():
Expand Down Expand Up @@ -278,6 +278,7 @@ def _translate_numbers(current, new, string):
translation_table = str.maketrans(current, new)
return string.translate(translation_table)


def normalize_string(serial_number, fixed_size=30):
""" gets a serial number and standardize it as following:
>> converts(removes others) all chars to English upper letters and numbers
Expand All @@ -301,7 +302,6 @@ def normalize_string(serial_number, fixed_size=30):
return f"{all_alpha}{missing_zeros}{all_digit}"



def check_serial(serial):
""" gets one serial number and returns appropriate
answer to that, after looking it up in the db
Expand Down Expand Up @@ -347,7 +347,6 @@ def check_serial(serial):
021-22038385""")
return 'OK', answer


answer = dedent(f"""\
{original_serial}
این شماره هولوگرام یافت نشد. لطفا دوباره سعی کنید و یا با واحد پشتیبانی تماس حاصل فرمایید.
Expand All @@ -374,34 +373,34 @@ def process():
db = get_database_connection()

cur = db.cursor()

log_new_sms(status, sender, message, answer, cur)

db.commit()
db.close()

send_sms(sender, answer)
ret = {"message": "processed"}
return jsonify(ret), 200



def log_new_sms(status, sender, message, answer, cur):
if len(message) > 40:
return
now = time.strftime('%Y-%m-%d %H:%M:%S')
cur.execute("INSERT INTO PROCESSED_SMS (status, sender, message, answer, date) VALUES (%s, %s, %s, %s, %s)", (status, sender, message, answer, now))

@app.errorhandler(404)
def page_not_found(error):
""" returns 404 page"""
return render_template('404.html'), 404



def create_sms_table():
"""Ctreates PROCESSED_SMS table on database if it's not exists."""
# Move all the tables creation scripts here, so that on startup all required tables will be created automatically.
def create_tables():
"""Creates PROCESSED_SMS table on database if they don't exist."""

db = get_database_connection()

cur = db.cursor()

try:
Expand All @@ -411,13 +410,14 @@ def create_sms_table():
message VARCHAR(400),
answer VARCHAR(400),
date DATETIME, INDEX(date, status));""")

db.commit()
except Exception as e:
flash(f'Error creating PROCESSED_SMS table; {e}', 'danger')

db.close()


create_tables() # create even if the module is running by UWSGI
if __name__ == "__main__":
create_sms_table()
app.run("0.0.0.0", 5000, debug=False)