如何通过psycop2g库,烧瓶和ajax从PostgreSQL数据库中获取和绘制数据?

发布于 2025-02-13 20:18:44 字数 7361 浏览 0 评论 0原文

您好,亲爱的Stackoverflow社区,我创建了一个名称为Epex的HREF链接(在我的HTML文件中),一个名称为Show Cartern。单击EPEX应抓取构建图形的X,y值的绘制图像(请参阅第一个PIC上传)。 X轴应表示时间轴,Y轴代表每1兆瓦的电力价格。

该脚本从我的PostgreSQL数据库(带有PsyCop2G)中获取文件,该文件最终保存在我的静态文件夹中new_plot.png。这里第一个图像链接:( https://ibb.co/bn29bv1

import psycopg2
#import numpy as np
import matplotlib.pyplot as plt

con = None
con = psycopg2.connect("dbname='Demonstratoren Statische Daten' user='postgres' password='NRL-HAW-2022' host='localhost'")
cur = con.cursor()
alles = ' SELECT * from "EPEX_2022" WHERE "id"=1 '

cur.execute(alles) 
rows = cur.fetchall()

for y in rows:
    #print("Id = ", y[0], )
    #print("Handelstag = ", y[1])
    #print("Durchschnittliche MWh Preise  = ", "\n", y[2:26] )
    #print(type(y[2:26]))
    print("Strompreise erfolreich abgerufen und abgespeichert!")
y_val = y[2:26]
#print ("zuletzt:", y_val)


# erhalte y[3:26] tuple, welches die stündlichen Strompreise pro MWh (als float numbers in postgresql hinterlegt)
# cursor abbruch, neue Abfrage der column namen aus postgresql, die unsere Abzisse darstellen mit x_val
con = None
con = psycopg2.connect("dbname='Demonstratoren Statische Daten' user='postgres' password='NRL-HAW-2022' host='localhost'")
con.autocommit = True
    
with con:
    with con.cursor() as cursor:
        cursor.execute(
            "select COLUMN_NAME from information_schema.columns\
            where table_name='EPEX_2022'")
        x0 = [row[0] for row in cursor] 
        x1= x0[2:]
        # Using list comprehension + list slicing method, um Zeitraum aus der x1 Liste zu löschen
        x_val = [sub[9 : ] for sub in x1]
        #print (x_val)
        
# giving a title to my graph
plt.title('EPEX-SPOTPRICE-DE - ' + str(y[1]))
plt.xlabel('Zeitraum (h)')
plt.ylabel('Durchschnittlicher Strompreis pro MWh (in €)')
plt.xticks(rotation=45, fontsize=3 )
plt.grid(True) 
plt.plot(x_val,y_val)
plt.plot(x_val,y_val,'or')
plt.savefig("EPEX-SPOTPRICE-DE - on "+ str(y[1]), dpi=300)
plt.show()

所以我的第一步是呈现我的页面上的Python脚本:

import psycopg2
import psycopg2.extras
from flask import (Flask,
    Blueprint,
    render_template
)
from flask_login import login_required, current_user
app = Flask(__name__)

import pandas as pd
import matplotlib.pyplot as plt
import os


server = Blueprint('server', __name__)
connectionString = "dbname='Demonstratoren Statische Daten' user='postgres' password='NRL-HAW-2022' host='localhost'"
conn = psycopg2.connect(connectionString)
try:
    conn = psycopg2.connect(connectionString)
 
    if conn is not None:
        print('Connection established to PostgreSQL.')
    else:
        print('Connection not established to PostgreSQL.')
         
except (Exception, psycopg2.DatabaseError) as error:
    print(error)


        
@server.route('/postgresql')
@login_required
def postgresql():
    return render_template('db.html', user=current_user)

        
@server.route('/postgresql/')
@login_required
def post():
  """rows returned from postgres are just an ordered list"""

  with conn:
      cur = conn.cursor()
      try:
          alles = ' Select "AG/TV", "Partner" from "Elektrolyseure" '
          cur.execute(alles)
      except:
              print("Error executing select")
  results = cur.fetchall()
  return render_template('db.html', Elektrolyseure=results,user=current_user)



    
@server.route('/postgresql/epex')
@login_required
def epex():
    return render_template('db.html', name = 'EPEX-SPOTPRICE-DE- 20 June 2022', url ='/static/Bilder/new_plot.png', user=current_user)

这是我的.html代码:

{% extends "base.html" %}

{% block content %}


  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
     
    <!-- Postgresqlabfragen -->
  </head>
  <body>
<div class="container-fluid">
  <div class="row">
    <nav id="sidebarMenu" class="col-md-3 col-lg-2 d-md-block bg-light sidebar collapse">
      <div class="position-sticky pt-3">
        <ul class="nav flex-column">
          
          <li class="nav-item">
            <a class="nav-link active" aria-current="page" href="{{url_for('server.epex')}}">
              <span data-feather="file"></span>
              EPEX
            </a>
          </li>
          <li class="nav-item">
            <a class="nav-link active" aria-current="page" href="{{url_for('server.post')}}">
              <span data-feather="file"></span>
              Show Partner
            </a>
          </li>
          
        </ul>
      </div>
    </nav>

    <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
      <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
        <h1 class="h2">EPEX Strompreise</h1>
        <div class="btn-toolbar mb-2 mb-md-0">
          <div class="btn-group me-2">
          </div>
          
  
  <div class="dropdown">
    <button type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown">
      Aktueller Stand
    </button>
    <ul class="dropdown-menu">
      <li><a class="dropdown-item" href="#">Letzte Woche</a></li>
      <li><a class="dropdown-item" href="#">Maximum</a></li>
    </ul>
  </div>
  
  
  
  
        </div>
      </div>
      
      
   

      <img src={{url}} width="900" height="600" >
      <br>
      <br>
      <h1>Elektrolyseur Tabelle</h1>

      <table>
      <tr><th>AG/TV</th><th>Partner</th></tr>
      {% for partner in Elektrolyseure %}
      <tr><td>{{partner[0]}}</td><td>{{partner[1]}}</td></tr>
      {% endfor %}
      </table>
      <br>
      <br>
      <head>
    <!--  </script><script src="{{ url_for('static', filename='EPEX_dashboard.js') }}"></script> -->
  </body>

{% endblock %}

我的问题是我渲染一个页面,其中包含此图片中所示的所有内容( https://ibb.co/0vqh7fl )。 我将所有3条路线作为图片上传,以解释它们应该如何显示:

  1. 输入/postgresql路线( https:// qjy6rsq ),让我使用Ajax请以右列中为中心。
  2. 单击EPEX应打开/postgresql/epex路由,并仅显示我的情节为图片( https://ibb.co/km5bjrjrj> )。其余的像“让我使用Ajax请”和“ Elektrolyseur Tabelle”消失了。
  3. 通过单击合作伙伴,U在链接/PostgreSQL/Partners上,所有红色都应被划出,例如此处( htttps:// ibb.co/bk4t5tz )。

有人可以帮我吗?再次感谢。

Hello dear Stackoverflow community, I have created a href link (in my html file) with the name EPEX and one with the name Show partner. Clicking on EPEX should grab of a ploted image, which are building the x,y values of my graph (see first pic upload). The x axis should represent the timeline and the y axis is representing the price for electricity per 1 Megawatt.

This script grabs files out of my postgresql database (with psycop2g) which saves at the end a new_plot.png in my static folder. Here the first image link: (https://ibb.co/bN29Bv1)

import psycopg2
#import numpy as np
import matplotlib.pyplot as plt

con = None
con = psycopg2.connect("dbname='Demonstratoren Statische Daten' user='postgres' password='NRL-HAW-2022' host='localhost'")
cur = con.cursor()
alles = ' SELECT * from "EPEX_2022" WHERE "id"=1 '

cur.execute(alles) 
rows = cur.fetchall()

for y in rows:
    #print("Id = ", y[0], )
    #print("Handelstag = ", y[1])
    #print("Durchschnittliche MWh Preise  = ", "\n", y[2:26] )
    #print(type(y[2:26]))
    print("Strompreise erfolreich abgerufen und abgespeichert!")
y_val = y[2:26]
#print ("zuletzt:", y_val)


# erhalte y[3:26] tuple, welches die stündlichen Strompreise pro MWh (als float numbers in postgresql hinterlegt)
# cursor abbruch, neue Abfrage der column namen aus postgresql, die unsere Abzisse darstellen mit x_val
con = None
con = psycopg2.connect("dbname='Demonstratoren Statische Daten' user='postgres' password='NRL-HAW-2022' host='localhost'")
con.autocommit = True
    
with con:
    with con.cursor() as cursor:
        cursor.execute(
            "select COLUMN_NAME from information_schema.columns\
            where table_name='EPEX_2022'")
        x0 = [row[0] for row in cursor] 
        x1= x0[2:]
        # Using list comprehension + list slicing method, um Zeitraum aus der x1 Liste zu löschen
        x_val = [sub[9 : ] for sub in x1]
        #print (x_val)
        
# giving a title to my graph
plt.title('EPEX-SPOTPRICE-DE - ' + str(y[1]))
plt.xlabel('Zeitraum (h)')
plt.ylabel('Durchschnittlicher Strompreis pro MWh (in €)')
plt.xticks(rotation=45, fontsize=3 )
plt.grid(True) 
plt.plot(x_val,y_val)
plt.plot(x_val,y_val,'or')
plt.savefig("EPEX-SPOTPRICE-DE - on "+ str(y[1]), dpi=300)
plt.show()

So my first step is to render my page with this python script:

import psycopg2
import psycopg2.extras
from flask import (Flask,
    Blueprint,
    render_template
)
from flask_login import login_required, current_user
app = Flask(__name__)

import pandas as pd
import matplotlib.pyplot as plt
import os


server = Blueprint('server', __name__)
connectionString = "dbname='Demonstratoren Statische Daten' user='postgres' password='NRL-HAW-2022' host='localhost'"
conn = psycopg2.connect(connectionString)
try:
    conn = psycopg2.connect(connectionString)
 
    if conn is not None:
        print('Connection established to PostgreSQL.')
    else:
        print('Connection not established to PostgreSQL.')
         
except (Exception, psycopg2.DatabaseError) as error:
    print(error)


        
@server.route('/postgresql')
@login_required
def postgresql():
    return render_template('db.html', user=current_user)

        
@server.route('/postgresql/')
@login_required
def post():
  """rows returned from postgres are just an ordered list"""

  with conn:
      cur = conn.cursor()
      try:
          alles = ' Select "AG/TV", "Partner" from "Elektrolyseure" '
          cur.execute(alles)
      except:
              print("Error executing select")
  results = cur.fetchall()
  return render_template('db.html', Elektrolyseure=results,user=current_user)



    
@server.route('/postgresql/epex')
@login_required
def epex():
    return render_template('db.html', name = 'EPEX-SPOTPRICE-DE- 20 June 2022', url ='/static/Bilder/new_plot.png', user=current_user)

Here is my .html code:

{% extends "base.html" %}

{% block content %}


  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
     
    <!-- Postgresqlabfragen -->
  </head>
  <body>
<div class="container-fluid">
  <div class="row">
    <nav id="sidebarMenu" class="col-md-3 col-lg-2 d-md-block bg-light sidebar collapse">
      <div class="position-sticky pt-3">
        <ul class="nav flex-column">
          
          <li class="nav-item">
            <a class="nav-link active" aria-current="page" href="{{url_for('server.epex')}}">
              <span data-feather="file"></span>
              EPEX
            </a>
          </li>
          <li class="nav-item">
            <a class="nav-link active" aria-current="page" href="{{url_for('server.post')}}">
              <span data-feather="file"></span>
              Show Partner
            </a>
          </li>
          
        </ul>
      </div>
    </nav>

    <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
      <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
        <h1 class="h2">EPEX Strompreise</h1>
        <div class="btn-toolbar mb-2 mb-md-0">
          <div class="btn-group me-2">
          </div>
          
  
  <div class="dropdown">
    <button type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown">
      Aktueller Stand
    </button>
    <ul class="dropdown-menu">
      <li><a class="dropdown-item" href="#">Letzte Woche</a></li>
      <li><a class="dropdown-item" href="#">Maximum</a></li>
    </ul>
  </div>
  
  
  
  
        </div>
      </div>
      
      
   

      <img src={{url}} width="900" height="600" >
      <br>
      <br>
      <h1>Elektrolyseur Tabelle</h1>

      <table>
      <tr><th>AG/TV</th><th>Partner</th></tr>
      {% for partner in Elektrolyseure %}
      <tr><td>{{partner[0]}}</td><td>{{partner[1]}}</td></tr>
      {% endfor %}
      </table>
      <br>
      <br>
      <head>
    <!--  </script><script src="{{ url_for('static', filename='EPEX_dashboard.js') }}"></script> -->
  </body>

{% endblock %}

My problem is that I render a page with everything like here seen in this picture (https://ibb.co/0Vqh7fL).
I uploaded all 3 routes as pictures, to explain how they should appear:

  1. Entering /postgresql route (https://ibb.co/qjY6RSq), let me use ajax please centered in the right column.
  2. Clicking on EPEX should open /postgresql/epex route and display only my plot as a picture (https://ibb.co/kM5BJRj). The rest like "let me use ajax please" and "Elektrolyseur Tabelle" is vanished.
  3. By Clicking partners, u are on the link /postgresql/partners and all red should be crossed out, like here (https://ibb.co/BK4T5tZ).

Can someone help me with it? Thanks again.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

⒈起吃苦の倖褔 2025-02-20 20:18:44

我将向您展示一个示例,其中每小时将显示“ ID完整(/MWH)”字段。我将制作一个像bar这样的图表。

import pandas as pd
import matplotlib.pyplot as plt

url = 'https://www.epexspot.com/en/market-data?market_area=DE&delivery_date=2022-07-06&underlying_year=&modality=Continuous&sub_modality=&product=60&data_mode=table&period='
df = pd.read_html(url)[0]
df = df.iloc[::7]
df.insert(0, "Hours", [f'{hour}-{hour + 1}' for hour in range(24)], True)
df.plot(kind='bar', x='Hours', y='ID Full(€/MWh)')
plt.show()

输出:

或您可以获取表结果:

print(df.to_string(index=False))

输出:

Hours  Low(€/MWh)  High(€/MWh)  Last(€/MWh)  Weight Avg.(€/MWh)  ID Full(€/MWh)  ID1(€/MWh)  ID3(€/MWh)  Buy Volume(MWh)  Sell Volume(MWh)  Volume(MWh)
  0-1      222.27       380.64       330.00              356.08          356.08      339.82      361.66           2933.6            3153.9       3043.8
  1-2      261.00       333.98       286.24              308.48          308.48      321.31      311.61           2790.7            3060.2       2925.5
  2-3      200.00       779.68       277.00              280.81          280.81      276.99      283.59           2533.9            2656.3       2595.1
  3-4      222.00       357.50       256.50              281.30          281.30      289.20      281.22           2508.5            3284.3       2896.4
  4-5      129.04       369.20       279.44              285.53          285.53      265.11      284.80           2432.5            3259.6       2846.1
  5-6     -204.01       806.09       295.00              304.25          304.25      311.77      304.15           1968.6            2845.3       2407.0
  6-7      269.30       390.47       375.78              367.43          367.43      362.03      371.35           2460.9            3151.7       2806.3
  7-8      283.84       424.48       345.81              393.43          393.43      402.92      403.66           2968.3            3344.8       3156.6
  8-9      297.92       427.45       319.80              393.39          393.39      403.53      398.48           2526.5            3271.5       2899.0
 9-10      265.12       369.15       315.89              332.16          332.16      302.10      332.42           3303.0            3888.7       3595.9
10-11      235.00       350.00       306.90              280.64          280.64      289.66      279.11           4079.0            4198.2       4138.6
11-12      202.50       880.55       500.00              281.35          281.35      288.10      264.60           5150.6            4958.4       5054.5
12-13      185.46       350.00       310.00              273.40          273.40      315.42      278.81           6634.5            5731.5       6183.0
13-14        5.00       492.95       151.00              221.91          221.91      204.65      237.88           7043.3            6219.9       6631.6
14-15      166.00       350.00       270.00              196.23          196.23      188.46      196.28           6408.5            5945.8       6177.2
15-16      100.00       194.19       144.54              166.22          166.22      138.91      163.06           6940.9            6470.0       6705.5
16-17      143.15       235.13       220.00              205.04          205.04      219.16      204.22           4851.3            5144.6       4998.0
17-18      231.51       449.90       439.00              292.16          292.16      324.29      300.02           4484.9            4569.0       4527.0
18-19      220.00       424.90       424.90              380.21          380.21      361.70      385.39           5226.5            4972.2       5099.4
19-20      243.00       488.00       243.00              435.11          435.11      391.27      436.54           5221.9            6069.3       5645.6
20-21      315.43       464.29       387.98              417.03          417.03      391.33      412.69           5329.6            5431.0       5380.3
21-22      314.53       649.99       475.10              417.28          417.28      417.78      407.66           5383.4            5147.6       5265.5
22-23      309.50       444.56       417.00              411.47          411.47      415.23      411.27           4553.3            4650.2       4601.8
23-24       88.93       500.00       370.70              362.71          362.71      384.00      368.79           4904.9            4687.9       4796.4

如果需要SQL,则可以轻松地将数据框架保存到SQL -

I will show you an example in which I will display the field 'ID Full(€/MWh)' for each hour. And I will make a chart like bar.

import pandas as pd
import matplotlib.pyplot as plt

url = 'https://www.epexspot.com/en/market-data?market_area=DE&delivery_date=2022-07-06&underlying_year=&modality=Continuous&sub_modality=&product=60&data_mode=table&period='
df = pd.read_html(url)[0]
df = df.iloc[::7]
df.insert(0, "Hours", [f'{hour}-{hour + 1}' for hour in range(24)], True)
df.plot(kind='bar', x='Hours', y='ID Full(€/MWh)')
plt.show()

OUTPUT:

Result plot

Or you can get table result:

print(df.to_string(index=False))

OUTPUT:

Hours  Low(€/MWh)  High(€/MWh)  Last(€/MWh)  Weight Avg.(€/MWh)  ID Full(€/MWh)  ID1(€/MWh)  ID3(€/MWh)  Buy Volume(MWh)  Sell Volume(MWh)  Volume(MWh)
  0-1      222.27       380.64       330.00              356.08          356.08      339.82      361.66           2933.6            3153.9       3043.8
  1-2      261.00       333.98       286.24              308.48          308.48      321.31      311.61           2790.7            3060.2       2925.5
  2-3      200.00       779.68       277.00              280.81          280.81      276.99      283.59           2533.9            2656.3       2595.1
  3-4      222.00       357.50       256.50              281.30          281.30      289.20      281.22           2508.5            3284.3       2896.4
  4-5      129.04       369.20       279.44              285.53          285.53      265.11      284.80           2432.5            3259.6       2846.1
  5-6     -204.01       806.09       295.00              304.25          304.25      311.77      304.15           1968.6            2845.3       2407.0
  6-7      269.30       390.47       375.78              367.43          367.43      362.03      371.35           2460.9            3151.7       2806.3
  7-8      283.84       424.48       345.81              393.43          393.43      402.92      403.66           2968.3            3344.8       3156.6
  8-9      297.92       427.45       319.80              393.39          393.39      403.53      398.48           2526.5            3271.5       2899.0
 9-10      265.12       369.15       315.89              332.16          332.16      302.10      332.42           3303.0            3888.7       3595.9
10-11      235.00       350.00       306.90              280.64          280.64      289.66      279.11           4079.0            4198.2       4138.6
11-12      202.50       880.55       500.00              281.35          281.35      288.10      264.60           5150.6            4958.4       5054.5
12-13      185.46       350.00       310.00              273.40          273.40      315.42      278.81           6634.5            5731.5       6183.0
13-14        5.00       492.95       151.00              221.91          221.91      204.65      237.88           7043.3            6219.9       6631.6
14-15      166.00       350.00       270.00              196.23          196.23      188.46      196.28           6408.5            5945.8       6177.2
15-16      100.00       194.19       144.54              166.22          166.22      138.91      163.06           6940.9            6470.0       6705.5
16-17      143.15       235.13       220.00              205.04          205.04      219.16      204.22           4851.3            5144.6       4998.0
17-18      231.51       449.90       439.00              292.16          292.16      324.29      300.02           4484.9            4569.0       4527.0
18-19      220.00       424.90       424.90              380.21          380.21      361.70      385.39           5226.5            4972.2       5099.4
19-20      243.00       488.00       243.00              435.11          435.11      391.27      436.54           5221.9            6069.3       5645.6
20-21      315.43       464.29       387.98              417.03          417.03      391.33      412.69           5329.6            5431.0       5380.3
21-22      314.53       649.99       475.10              417.28          417.28      417.78      407.66           5383.4            5147.6       5265.5
22-23      309.50       444.56       417.00              411.47          411.47      415.23      411.27           4553.3            4650.2       4601.8
23-24       88.93       500.00       370.70              362.71          362.71      384.00      368.79           4904.9            4687.9       4796.4

If SQL is required, you can easy save dataframe to SQL - DataFrame.to_sql()

一人独醉 2025-02-20 20:18:44

好的,也许我的问题很难理解,但是我想最终发布一个解决方案,该解决方案使用Ajax回答了我的问题。

import psycopg2
#import numpy as np
import matplotlib.pyplot as plt



def generate_epex_plot(id: str):
    print("generate_epex_plot called, id=", id)
    con = None
    con = psycopg2.connect("dbname='Demonstratoren Statische Daten' user='postgres' password='NRL-HAW-2022' host='localhost'")
    cur = con.cursor()
    query =  f' SELECT * from "EPEX_2022" WHERE "id"={id}'
    if id =="0":
        query = ' SELECT * from "EPEX_2022" ORDER by id DESC LIMIT 1'
    #print("query:", query)
    cur.execute(query) 
    rows = cur.fetchall()
    #print(rows)
    #y_val = None
    y = rows[0]
    #print("Id = ", y[0], )
    #print("Handelstag = ", y[1])
    #print("Durchschnittliche MWh Preise  = ", "\n", y[2:26] )
    print(type(y[2:26]))
    print(y)
    print("Strompreise erfolgreich abgerufen und abgespeichert!")
    y_val = y[2:26]
    #print ("zuletzt:", y_val)
    
    
    # erhalte y[3:26] tuple, welches die stündlichen Strompreise pro MWh (als float numbers in postgresql hinterlegt)
    # cursor abbruch, neue Abfrage der column namen aus postgresql, die unsere Abzisse darstellen mit x_val
    con = None
    con = psycopg2.connect("dbname='Demonstratoren Statische Daten' user='postgres' password='NRL-HAW-2022' host='localhost'")
    con.autocommit = True
        
    with con:
        with con.cursor() as cursor:
            cursor.execute(
                "select COLUMN_NAME from information_schema.columns\
                where table_name='EPEX_2022'")
            x0 = [row[0] for row in cursor] 
            print( "x0", x0)
            x1= x0[2:26]
            print( "x1", x1)
            # Using list comprehension + list slicing method, um Zeitraum aus der x1 Liste zu löschen
            x_val = [sub[9 : ] for sub in x1]
            print ( "xval", x_val)
            
    # giving a title to my graph
    plt.title('EPEX-SPOTPRICE-DE - ' + str(y[1]))
    plt.xlabel('Zeitraum (h)')
    plt.ylabel('Durchschnittlicher Strompreis pro MWh (in €)')
    plt.xticks(rotation=45, fontsize=3 )
    plt.grid(True) 
    plt.plot(x_val,y_val)
    plt.plot(x_val,y_val,'or')
    #plt.savefig("static/Bilder/new_plot.png", dpi = 150) 
    plt.savefig("website/static/Bilder/new_plot.png", dpi = 150)
    plt.close()
    
    #plt.savefig("EPEX-SPOTPRICE-DE - on "+ str(y[1]), dpi=300)
    #plt.show()

if __name__ == "__main__":
    generate_epex_plot("0")
    print("Plot created!")

为此,我必须更改我的HTML代码并使用JavaScript。

{% extends "base.html" %}

{% block content %}


  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
     
    <!-- Postgresqlabfragen -->
  </head>
  <body>
<div class="container-fluid">
  <div class="row">
    <nav id="sidebarMenu" class="col-md-3 col-lg-2 d-md-block bg-light sidebar collapse">
      <div class="position-sticky pt-3">
        <ul class="nav flex-column">
        <ul>
          <li> <strong>Verfügbare Abfragen:</strong> </li>
          </ul>
          <li class="nav-item">
            <a class="nav-link active" aria-current="page" href="{{url_for('server.epex')}}">
              EPEX
            </a>
          </li>
          <li class="nav-item">
            <a class="nav-link active" aria-current="page" href="{{url_for('server.post')}}">
              Show Partner
            </a>
          </li>
          
        </ul>
      </div>
    </nav>

    <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
      <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
        <h1 class="h2">EPEX Strompreise</h1>
        <div class="btn-toolbar mb-2 mb-md-0">
          <div class="btn-group me-2">
          </div>
          
 
  <div class="dropdown">
    <button type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown">
      Aktueller Stand
    </button>
    <ul class="dropdown-menu">
      <li><a class="dropdown-item" onclick="loadNewGraph(1)">Aktueller Stand</a></li>
      <li><a class="dropdown-item" onclick="loadNewGraph(1)">Letzte Woche</a></li>
      <li><a class="dropdown-item" onclick="loadNewGraph(2)">Maximum</a></li>
    </ul>
  </div>
  
        </div>
      </div>

      <img id="graph" src="" width="900" height="600" >
      
    <!-- <script src="{{ url_for('static', filename='EPEX_dashboard.js') }}"></script>-->
    <script>
    function loadNewGraph(id){
    
    let req_url = '/postgresql/epex/get_graph/'
    //if (window.location.href.includes("partner")){
    //    req_url = '/postgresql/partner/get_graph/'
    //}
    
    
    // ajax call to url get_graph, cf.: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
    const xhttp = new XMLHttpRequest();
    xhttp.open("GET", req_url + id, true);
    xhttp.send();
    
    xhttp.onload = function(e){
        imgurl = document.getElementById('graph')
        imgurl.src = '/static/Bilder/new_plot.png' + "?ts=" + Date.now()
        
    }

    
    }
    loadNewGraph(0)
    </script>
  </body>

{% endblock %}

无论如何。谢谢谢尔盖,你也向我展示了一些技巧:-)。

Ok, maybe my question was too hard to understand, but I wanted to post finally a solution, which answers my question using AJAX.

import psycopg2
#import numpy as np
import matplotlib.pyplot as plt



def generate_epex_plot(id: str):
    print("generate_epex_plot called, id=", id)
    con = None
    con = psycopg2.connect("dbname='Demonstratoren Statische Daten' user='postgres' password='NRL-HAW-2022' host='localhost'")
    cur = con.cursor()
    query =  f' SELECT * from "EPEX_2022" WHERE "id"={id}'
    if id =="0":
        query = ' SELECT * from "EPEX_2022" ORDER by id DESC LIMIT 1'
    #print("query:", query)
    cur.execute(query) 
    rows = cur.fetchall()
    #print(rows)
    #y_val = None
    y = rows[0]
    #print("Id = ", y[0], )
    #print("Handelstag = ", y[1])
    #print("Durchschnittliche MWh Preise  = ", "\n", y[2:26] )
    print(type(y[2:26]))
    print(y)
    print("Strompreise erfolgreich abgerufen und abgespeichert!")
    y_val = y[2:26]
    #print ("zuletzt:", y_val)
    
    
    # erhalte y[3:26] tuple, welches die stündlichen Strompreise pro MWh (als float numbers in postgresql hinterlegt)
    # cursor abbruch, neue Abfrage der column namen aus postgresql, die unsere Abzisse darstellen mit x_val
    con = None
    con = psycopg2.connect("dbname='Demonstratoren Statische Daten' user='postgres' password='NRL-HAW-2022' host='localhost'")
    con.autocommit = True
        
    with con:
        with con.cursor() as cursor:
            cursor.execute(
                "select COLUMN_NAME from information_schema.columns\
                where table_name='EPEX_2022'")
            x0 = [row[0] for row in cursor] 
            print( "x0", x0)
            x1= x0[2:26]
            print( "x1", x1)
            # Using list comprehension + list slicing method, um Zeitraum aus der x1 Liste zu löschen
            x_val = [sub[9 : ] for sub in x1]
            print ( "xval", x_val)
            
    # giving a title to my graph
    plt.title('EPEX-SPOTPRICE-DE - ' + str(y[1]))
    plt.xlabel('Zeitraum (h)')
    plt.ylabel('Durchschnittlicher Strompreis pro MWh (in €)')
    plt.xticks(rotation=45, fontsize=3 )
    plt.grid(True) 
    plt.plot(x_val,y_val)
    plt.plot(x_val,y_val,'or')
    #plt.savefig("static/Bilder/new_plot.png", dpi = 150) 
    plt.savefig("website/static/Bilder/new_plot.png", dpi = 150)
    plt.close()
    
    #plt.savefig("EPEX-SPOTPRICE-DE - on "+ str(y[1]), dpi=300)
    #plt.show()

if __name__ == "__main__":
    generate_epex_plot("0")
    print("Plot created!")

And for this i had to change my html code and use javascript.

{% extends "base.html" %}

{% block content %}


  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
     
    <!-- Postgresqlabfragen -->
  </head>
  <body>
<div class="container-fluid">
  <div class="row">
    <nav id="sidebarMenu" class="col-md-3 col-lg-2 d-md-block bg-light sidebar collapse">
      <div class="position-sticky pt-3">
        <ul class="nav flex-column">
        <ul>
          <li> <strong>Verfügbare Abfragen:</strong> </li>
          </ul>
          <li class="nav-item">
            <a class="nav-link active" aria-current="page" href="{{url_for('server.epex')}}">
              EPEX
            </a>
          </li>
          <li class="nav-item">
            <a class="nav-link active" aria-current="page" href="{{url_for('server.post')}}">
              Show Partner
            </a>
          </li>
          
        </ul>
      </div>
    </nav>

    <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
      <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
        <h1 class="h2">EPEX Strompreise</h1>
        <div class="btn-toolbar mb-2 mb-md-0">
          <div class="btn-group me-2">
          </div>
          
 
  <div class="dropdown">
    <button type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown">
      Aktueller Stand
    </button>
    <ul class="dropdown-menu">
      <li><a class="dropdown-item" onclick="loadNewGraph(1)">Aktueller Stand</a></li>
      <li><a class="dropdown-item" onclick="loadNewGraph(1)">Letzte Woche</a></li>
      <li><a class="dropdown-item" onclick="loadNewGraph(2)">Maximum</a></li>
    </ul>
  </div>
  
        </div>
      </div>

      <img id="graph" src="" width="900" height="600" >
      
    <!-- <script src="{{ url_for('static', filename='EPEX_dashboard.js') }}"></script>-->
    <script>
    function loadNewGraph(id){
    
    let req_url = '/postgresql/epex/get_graph/'
    //if (window.location.href.includes("partner")){
    //    req_url = '/postgresql/partner/get_graph/'
    //}
    
    
    // ajax call to url get_graph, cf.: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
    const xhttp = new XMLHttpRequest();
    xhttp.open("GET", req_url + id, true);
    xhttp.send();
    
    xhttp.onload = function(e){
        imgurl = document.getElementById('graph')
        imgurl.src = '/static/Bilder/new_plot.png' + "?ts=" + Date.now()
        
    }

    
    }
    loadNewGraph(0)
    </script>
  </body>

{% endblock %}

Anyways. Thank you Sergey, you showed me also me some trick :-).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文