我正在嘗試為燒瓶中的生產和開發環境配置我的 postgresql。現在我的配置僅適用于本地環境。我也想讓它適用于生產。它是這樣的:
app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql://username:password@localhost:5432/database"
現在在這個專案中完成的所有作業包括資料庫配置都包含在 app.py 檔案中。我還有一個索引函式,我每 5 分鐘間隔運行一次。間隔值來自資料庫。這是我的 app.py 檔案。
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()
任何方式我都可以通過更好的檔案夾結構安排以更好的方式組織這個專案。此外,在運行調度程式的專案上也應該作業。任何關于此的建議將不勝感激
uj5u.com熱心網友回復:
要為燒瓶應用程式生產電離環境變數,我建議您查看https://flask.palletsprojects.com/en/2.0.x/config/#development-production
基本思想是有一個帶有字典的配置類,其中鍵定義為
config = {"development":DevelopmentConfig, "production": ProductionConfig}
此配置__init__.py在應用程式的最開始加載。您將使用 .env 配置根據指定的環境加載不同的配置。最后,您可以 dockerize 整個應用程式。
uj5u.com熱心網友回復:
首先,您可以針對不同的環境使用不同的配置。您可以在此處找到更多資訊:燒瓶生產和開發模式。
你也可以考慮flask中的應用工廠模式:https : //flask.palletsprojects.com/en/2.0.x/patterns/appfactories/
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/380532.html
