Home > Mobile >  flask postgresql sqlalchemy configuration for production and development
flask postgresql sqlalchemy configuration for production and development

Time:12-10

I am trying to configure my postgresql for both production and development envronment in flask.Right now my configuration only works for local environment.I want to also make it work for production.This is it how it looks like:

app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql://username:password@localhost:5432/database"

Right now all the work done in this project including database configuration consists in app.py file.I have also one index function which i run every 5 min interval.The interval value comes from database.This is my app.py file.

    from flask import Flask, render_template, Response, json
    from flask_sqlalchemy import SQLAlchemy
    from bs4 import BeautifulSoup
    import requests
    from sqlalchemy import text
    import uuid
    from stockDto import StockDto
    import schedule
    import time
    
    stockDtoList = StockDto(many=True)
    
    app = Flask(__name__)
    
    db = SQLAlchemy(app)
    
    app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql://username:password@localhost:5432/database"
    
    
    def generate_uuid():
        return str(uuid.uuid4())
    
            
    class StockStatus(db.Model):
        __tablename__ = 'stockstatus'
        id = db.Column(db.String, primary_key=True, default=generate_uuid)
        name = db.Column(db.Text)
        ltp = db.Column(db.Text)
        high = db.Column(db.Text)
        low = db.Column(db.Text)
    
    
    @app.route('/stockList', methods=['GET'])
    def getStock():
        try:
            articles = StockStatus.query.all()
            resultList = stockDtoList.dump(articles)
            return Response(json.dumps({'status': 'success', 'message': 'data Found', 'data': resultList}),
                            status=200, mimetype='application/json')
    
        except Exception as e:
            print('exception is :: ', e)
            return Response(json.dumps({'status': 'failed', 'message': 'data failed  to get'}),
                            status=500, mimetype='application/json')
    
    
    # @app.route('/')
    def index():
        connection = db.engine.connect(close_with_result=True)
        print('first')
    
        sql = text("""delete from stockstatus""")
        print('done')
        connection.execute(sql)
        connection.close()
        r = requests.get("http://www.dsebd.org/latest_share_price_scroll_l.php")
        # Create a BeautifulSoup object
        soup = BeautifulSoup(r.content, 'html5lib')
        soup.prettify()
        table = soup.find('table', attrs={
            'class': 'table table-bordered background-white shares-table fixedHeader'})
        quotes = []  # a list to store quotes
        for row in table.find_all('tr')[1:]:
            cols = row.find_all('td')
            quotes.append({'name': cols[1].text.strip().replace(",", ""),
                           'ltp': cols[2].text.strip().replace(",", ""),
                           'high': cols[3].text.strip().replace(",", ""),
                           'low': cols[4].text.strip().replace(",", ""),
                           })
    
        for SidesValue in quotes:
            dataMedia = StockStatus(
                name=SidesValue['name'],
                ltp=SidesValue['ltp'],
                high=SidesValue['high'],
                low=SidesValue['low'],
            )
    
            db.session.add(dataMedia)
            db.session.commit()
        articles = StockStatus.query.all()
    
        # return render_template("index.html", articles=articles)
    connection = db.engine.connect(close_with_result=True)
    sqlUpdate = text("""select schedulevalue from stocksettings""")
    scheduleStatus = connection.execute(sqlUpdate).fetchone()
    dataInterval = int(scheduleStatus['schedulevalue'])
    print(dataInterval)
    schedule.every(dataInterval).minutes.do(index)
    # scheduler wait for 5 mins
    while True:
        schedule.run_pending()
        time.sleep(dataInterval)
    if __name__ == "__main__":
        app.run()

Any way i can organize this project in a better way with better folder structure arrangement.Also upon the project running the scheduler also should work.ANy suggestion regarding this would be appreciated

CodePudding user response:

To product ionize environment variables for a flask application, I would suggest you to take a look at https://flask.palletsprojects.com/en/2.0.x/config/#development-production

The basic idea is to have a config class with a dictionary where key is defined as

config = {"development":DevelopmentConfig, "production": ProductionConfig}

This configuration is loaded in __init__.py the very beginning of the application. You would use .env configuration to load different configuration according to the specified environment. Finally, you can dockerize the entire application.

CodePudding user response:

  1. First you can have different config for different environment. More you find here: flask production and development mode.

  2. You can also think about application factory pattern in flask: https://flask.palletsprojects.com/en/2.0.x/patterns/appfactories/

  • Related