Python Folder structure for Scheduling Tasks

In this example I have a server where there is folder “long_script” folder. Under that folder I have keep all ".py" files

Folder structure can be :

In the above structure I run users.py file by following command:

Cd /var/www/html/long_script python users.py

Config.py contain all configuration variables, so content are:

database_user = test database_pass = '123456' database_host = 'hostname' database_name = ‘dbname’ #local report upload url local_report_upload_url = '/var/www/html/assets/uploads/'

Database.py contain database connecting class:

import config.config as cf import pymysql class Databseconnection: @staticmethod def fetch_dbconnection(): try: db = pymysql.connect(cf.database_host, cf.database_user, cf.database_pass, cf.database_name, charset='utf8',autocommit=True) return db except Exception as error: print('Error: Mysql connection not established {}'.format(error)) exit() @staticmethod def close_dbconnection(db): db.close()

Now under “users” folder from UseController.py, I call above database class:

from users.userModel import userModel as usermModel class UserController(): def fetch(self): users = Userm() data = users.fetch() for fetchPostContent in data: print(fetchPostContent[0])

Content of userModel.py under “users” folder:

from config.dbconnection import Dbconnection as Dbc class UserModel(): def __init__(self): self.db = Dbc.get_connection() self.cur = self.db.cursor() def fetch(self): self.cur.execute('SELECT * from users') data = self.cur.fetchall() return data def __del__(self): self.cur.close() Dbc.close_connection(self.db)

In this above file in destructor I closed db connection, that will manage db connections. Now from users.py file I call controller’s function :

from users.userController import userController as userCon usrc = UserCon() usrc.fetch()

In this above struction I add one .htaccess file in root of python folder to restrict content of .py file from browser. This is very important for security reason:

RewriteEngine On RewriteCond %{HTTP_REFERER} !^(https?://)?abc.com RewriteRule ^/?long_script/ - [L,F] # Hide the contents of directories IndexIgnore *

Follow me on

Share it