所以我对flask还是个新手,目前我正在尝试为我正在从事的一个项目创建一个flask api。然而,我面临着几个问题。
因此,对于我的第一个问题,我不能从第一个函数中获取数据帧,以便在第二个函数中工作。我只是想知道怎样才能让data_1在第二个函数中工作。
代码:
from flask import Flask
from sqlalchemy import create_engine
import sqlite3 as sql
import pandas as pd
import datetime
import os
app = Flask(__name__)
@app.route('/', methods=['GET'])
def get_data():
...
data_1 = ...
#print(data_1.head(n=10))
return "hello"
@app.route('/table1', methods=['GET'])
def store_table1_data_df():
db_path = os.path.join(os.path.dirname(__file__),'table1.db')
engine = create_engine('sqlite:///{}'.format(db_path), echo=True)
sqlite_connection = engine.connect()
sqlite_table = 'table1'
data_1.to_sql(sqlite_table,sqlite_connection, if_exists='append')
sqlite_connection.close()
return "table1"对于我的第二个问题,有没有更好的方法在flask api中使用sqlalchemy或sqlite3来存储数据帧?
更多关于data_1是什么的上下文:data_1只能保存过去15天/记录,比如从2021年6月15日到2021年6月30日。但是,明天,如果我获取最新的data_1,它将包含6/16/2021-7/01/2021。我如何才能将07/01/2021附加到旧的data_1,而不会从06/16/2021创建重复的记录,创建另外两个函数和一个额外的db文件?
@app.route('/table1', methods=['GET'])
def store_table1_data_df():
db_path = os.path.join(os.path.dirname(__file__),'table1.db')
engine = create_engine('sqlite:///{}'.format(db_path), echo=True)
sqlite_connection = engine.connect()
sqlite_table = 'table1'
data_1.to_sql(sqlite_table,sqlite_connection, if_exists='append')
sqlite_connection.close()
return "table1"
@app.route('/table2', methods=['GET'])
def store_table2_data_df():
db_path2 = os.path.join(os.path.dirname(__file__),'table2.db')
engine2 = create_engine('sqlite:///{}'.format(db_path2), echo=True)
sqlite_connection2 = engine2.connect()
sqlite_table2 = 'table2'
data_1.to_sql(sqlite_table2,sqlite_connection2, if_exists='append')
sqlite_connection2.close()
return "table2"
# What I probably have down below is not the correct way to solve this problem
@app.route('/table1', methods=['GET'])
conn = sql.connect("table1.db")
cur = conn.cursor()
#cur.execute
cur.execute("ATTACH 'table2.db' as 'table2' ")
conn.commit()
table_3 = pd.read_sql_query("SELECT DISTINCT date, value FROM table1 UNION SELECT DISTINCT date, value from table2 ORDER BY date", conn)
cur.execcute("SELECT DISTINCT date, value FROM table1 UNION SELECT DISTINCT date, value from table2 ORDER BY date")
conn.commit()
results3 = cur.fetchall()
sqlite_table='table1'
table_3.to_sql(sqlite_table, conn, if_exists='replace')
cur.close()
conn.close()
return "work"任何帮助都是非常感谢的。
发布于 2021-07-01 13:48:28
对于你的第一个问题。您可以执行以下任一操作:
def getdata1(val1, val2):
#calculation here
return data_1只要你需要data_1就调用它。
对于第二部分,将使用一个简单的For循环。关于这点的提示:
sql_table = ["Fetch your sql table here with the dataframe. Considering dates in one column"]
data_1 = ["Your dataframe"]
for i in data_1['Dates']:
if i != sql_table['dates']:
#insert this key:value pair in sql table如果您的数据框和sql是按日期顺序加载的,那就更好了。你只需要检查每一个的最后一个元素。
https://stackoverflow.com/questions/68201525
复制相似问题