'flask'에 해당되는 글 1건

  1. 2023.02.04 sample python code with PostgreSQL

 

example of a Python Flask application that uses a PostgreSQL database to store the daily work of employees:

 

import psycopg2
from flask import Flask, request, render_template
app = Flask(__name__)

def get_conn():
    conn = psycopg2.connect(
        host="localhost",
        database="daily_work",
        user="postgres",
        password="secret"
    )
    return conn

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/submit_work", methods=["POST"])
def submit_work():
    work = request.form["work"]
    conn = get_conn()
    cur = conn.cursor()
    cur.execute("INSERT INTO work (description) VALUES (%s)", (work,))
    conn.commit()
    cur.close()
    conn.close()
    return "Work submitted successfully!"

if __name__ == "__main__":
    app.run()

This code uses the Flask web framework and the psycopg2 library to interact with a PostgreSQL database. The get_conn function returns a connection to the database, and the submit_work route uses this connection to insert the work submitted by the employee into the work table. You'll need to create this table and the daily_work database using a tool like the psql client or a GUI client like pgAdmin. The table can be created with the following SQL command:

 

CREATE TABLE work (
    id serial PRIMARY KEY,
    description text NOT NULL
);
<html>
  <head>
    <title>Enter daily work</title>
  </head>
  <body>
    <form action="/submit_work" method="post">
      <textarea name="work"></textarea>
      <input type="submit" value="Submit work">
    </form>
  </body>
</html>

 

sample code to show the contents stored in the PostgreSQL database as a table:

import psycopg2
from flask import Flask, render_template
app = Flask(__name__)

def get_conn():
    conn = psycopg2.connect(
        host="localhost",
        database="daily_work",
        user="postgres",
        password="secret"
    )
    return conn

@app.route("/")
def index():
    conn = get_conn()
    cur = conn.cursor()
    cur.execute("SELECT * FROM work")
    work = cur.fetchall()
    cur.close()
    conn.close()
    return render_template("work_table.html", work=work)

if __name__ == "__main__":
    app.run()

 

php

<html>
  <head>
    <title>Daily work</title>
  </head>
  <body>
    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>Description</th>
        </tr>
      </thead>
      <tbody>
        {% for row in work %}
        <tr>
          <td>{{ row[0] }}</td>
          <td>{{ row[1] }}</td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
  </body>
</html>

This code uses the Flask web framework and the psycopg2 library to interact with a PostgreSQL database. The index route retrieves the work stored in the work table using a SQL query, and the template work_table.html displays the work as a table.

Posted by 마인드파워
,