Получение данных через REST API и как сохранить их в базе данных mysql?

#python #mysql #pandas #web-scraping #rest

#python #mysql #pandas #веб-очистка #rest

Вопрос:

Я только что получил данные через REST API и хотел сохранить их в базе данных mysql. Поскольку я новичок, просто ищу способ сохранить данные в моей базе данных sql. Не могли бы вы, ребята, предложить мне какой-нибудь учебник / библиотеку / пример. Это было бы большим подспорьем. Спасибо. И если я против условий и условий stackoverflow, мне очень жаль. Но мне действительно нужна помощь по этой теме.

 **from entsoe import EntsoePandasClient
import pandas as pd

client = EntsoePandasClient(api_key='api-key')

start = pd.Timestamp('20171201', tz='Europe/Brussels')
end = pd.Timestamp('20180101', tz='Europe/Brussels')
country_code = 'BE'  # Belgium

# methods that return Pandas Series
client.query_day_ahead_prices(country_code, start=start,end=end)
client.query_load(country_code, start=start,end=end)
client.query_load_forecast(country_code, start=start,end=end)
client.query_generation_forecast(country_code, start=start,end=end)

# methods that return Pandas DataFrames
client.query_wind_and_solar_forecast(country_code, start=start,end=end, psr_type=None)
client.query_generation(country_code, start=start,end=end, psr_type=None)
client.query_installed_generation_capacity(country_code, start=start,end=end, psr_type=None)
client.query_crossborder_flows('DE', 'DK', start=start,end=end)
client.query_imbalance_prices(country_code, start=start,end=end, psr_type=None)
client.query_unavailability_of_generation_units(country_code, start=start,end=end, docstatus=None)
#client.query_withdrawn_unavailability_of_generation_units('DE', start=start,end=end)

ts = client.query_day_ahead_prices(country_code, start=start, end=end)
print(ts)**
  

Ответ №1:

Используя to_sql функцию, предоставляемую pandas, все, что вам нужно, это передать объект соединения, созданный с SQLAlchemy помощью библиотеки :

 from sqlalchemy import create_engine
engine = create_engine("mysql pymysql://root:pass@localhost/mydb")

df.to_sql('table_name_for_df', con=engine, if_exists='append', flavor='mysql')
# check if the data has been sent
engine.execute("SELECT * FROM table_name_for_df").fetchall()