1- import uuid
2- import datetime
3- import string
41import random
5- from urllib .parse import urlparse as url_parse
6- from celery import Celery , Task
7- from flask import Flask , current_app , request , session
8- from werkzeug .utils import secure_filename as werkzeug_secure_filename
9-
10- SysRandom = random .SystemRandom ()
2+ import string
113
124
13- def generate_random_string (length : int = 6 , punctuation : bool = True ) -> str :
5+ SysRandom = random .SystemRandom ()
6+ def generate_random_string (length : int = 3 , punctuation : bool = False ) -> str :
147 """generate random strings
15-
168 params:
179 length: int = length of random string - default is 6
1810 punctuation: bool = punctuation in random string or not
19-
2011 return:
2112 str: string: random string
2213 """
@@ -26,44 +17,3 @@ def generate_random_string(length: int = 6, punctuation: bool = True) -> str:
2617 random_string = SysRandom .choices (letters , k = length )
2718
2819 return "" .join (random_string )
29-
30-
31- def get_next_page (fall_back_url : str = '' ) -> str :
32- """
33- use this method for validating next params in url
34- validate http url args next=some url
35- """
36- next_page = request .args .get ("next" , False )
37- if not next_page or url_parse (next_page ).netloc != "" :
38- next_page = fall_back_url
39-
40- return next_page
41-
42-
43-
44- def make_file_name_secure (name : str , round :int = 3 ):
45- """This function make sure a file name is secure
46- remove dangerous characters and add uuid to first of file name
47- """
48- name = name .replace (" " , "" )
49- name = werkzeug_secure_filename (name )
50- return f"{ '' .join ([uuid .uuid4 ().hex for _ in range (round )])} -{ datetime .datetime .utcnow ().date ()} -{ name } "
51-
52-
53- def celery_init_app (app : Flask ) -> Celery :
54- class FlaskTask (Task ):
55- """Every time a task is added to queue
56- __call__ ...
57- """
58-
59- def __call__ (self , * args : object , ** kwargs : object ) -> object :
60- with app .app_context ():
61- return self .run (* args , ** kwargs )
62-
63- celery_app = Celery (app .name , task_cls = FlaskTask )
64- celery_app .config_from_object (app .config ["CELERY" ])
65- celery_app .Task = FlaskTask
66- celery_app .set_default ()
67- app .extensions ["celery" ] = celery_app
68- return celery_app
69-
0 commit comments