2024年1月10日 星期三

咖啡廳紀錄 Flask

 


from flask import Flask, render_template,url_for
from flask_bootstrap import Bootstrap5
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField

from wtforms.validators import DataRequired
import csv

'''
Red underlines? Install the required packages first:
Open the Terminal in PyCharm (bottom left).

On Windows type:
python -m pip install -r requirements.txt

On MacOS type:
pip3 install -r requirements.txt

This will install the packages from requirements.txt for this project.
'''

app = Flask(__name__)
app.config['SECRET_KEY'] = '8BYkEfBA6O6donzWlSihBXox7C0sKR6b'
bootstrap = Bootstrap5(app)


class CafeForm(FlaskForm):
    cafe = StringField('Cafe name', validators=[DataRequired()])
    location = StringField('Location',validators=[DataRequired()])
    open = StringField('open',validators=[DataRequired()])
    close = StringField('close',validators=[DataRequired()])
    coffee = StringField('coffee',validators=[DataRequired()])
    wifi = StringField('wifi',validators=[DataRequired()])
    power = StringField('power',validators=[DataRequired()])

    submit = SubmitField('Submit')


#Cafe Name,Location,Open,Close,Coffee,Wifi,Power
# Exercise:
# add: Location URL, open time, closing time, coffee rating, wifi rating, power outlet rating fields
# make coffee/wifi/power a select element with choice of 0 to 5.
#e.g. You could use emojis ☕️/💪/✘/🔌
# make all fields required except submit
# use a validator to check that the URL field has a URL entered.
# ---------------------------------------------------------------------------


# all Flask routes below
@app.route("/")
def home():
    return render_template("index.html")


@app.route('/add',methods=['GET','POST'])
def add_cafe():
    form = CafeForm()
    if form.validate_on_submit():
        print("True")
        # with open('cafe-data.csv',newline='',encoding='utf-8')as csv_file:
        #     csv_data = csv.reader(csv_file,delimiter=',')
        #     list_of_row = []
        #     for row in csv_data:
        #         list_of_row.append(row)
        # print(f'list_of_row={list_of_row}')
        # print(f'提交後form={form.data}')
        new_list=[]
        i=0
        for val in form.data.values():
            print(f'va={val}')
            new_list.append(val)
            i+=1 #只有前7項
            if i ==7:
                break
        print(f'new_list={new_list}')
        with open('cafe-data.csv',mode='a',newline='\n',encoding='utf-8')as csv_file:
            csv_writer = csv.writer(csv_file,delimiter=',')
            csv_writer.writerow(new_list)
        # list_of_row.append(new_list)

               
    # Exercise:
    # Make the form write a new row into cafe-data.csv
    # with   if form.validate_on_submit()
    return render_template('add.html', form=form)


@app.route('/cafes')
def cafes():
    with open('cafe-data.csv', newline='', encoding='utf-8') as csv_file:
        csv_data = csv.reader(csv_file, delimiter=',')
        list_of_rows = []
        for row in csv_data:
            list_of_rows.append(row)
        # print(f'list={list_of_rows}')
        for row in list_of_rows:
            print(f'row={row}')
            print(f'row[0]={row[0]}')
            print(f'row[1]={row[1]}')

    return render_template('cafes.html', data=list_of_rows)


if __name__ == '__main__':
    app.run(debug=True)


------base.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />

    {% block styles %}
    <!-- Load Bootstrap-Flask CSS here -->
    {{bootstrap.load_css()}}

    <!-- Link to the styles.css here to apply styling to all the child templates.-->
    <link rel="stylesheet" href="../static/css/styles.css">

    {% endblock %}
    <title>{% block title %}{% endblock %}</title>
  </head>
  <body>
    {% block content %}{% endblock %}
    {% block scripts %}
    {{bootstrap.load_js()}}
    {% endblock %}
  </body>
</html>


------index.html


{% extends 'base.html' %}
{% block title %}Coffee and Wifi{% endblock %}

{% block content %}
<div class="jumbotron text-center">
    <div class="container">
  <h1 class="display-4">☕️ Coffee & Wifi 💻</h1>
  <p class="lead">Want to work in a cafe but need power and wifi?</p>
  <hr class="my-4">
  <p>You've found the right place! Checkout my collection of cafes with data on power socket availability, wifi speed and coffee quality.</p>
 
  <a class="btn btn-warning btn-lg mx-4" href="{{url_for('cafes')}}" role="button">SHOW ME!</a>
  <a class="btn btn-warning btn-lg mx-4" href="{{url_for('add_cafe')}}" role="button">ADD IT!</a>

</div>
    </div>

{% endblock %}



-------------add.html

{% extends 'base.html' %}
<!--Don't forget your import here-->
{% block title %}Add A New Cafe{% endblock %}
<!-- {% from 'bootstrap5/form.html' import render_form %} -->
{% block content %}
<div class="container">
  <div class="row">
    <div class="col-sm-12 col-md-8">

      <h1>Add a new cafe into the database</h1>

      <!-- This is where your WTForm will go -->
      <form method="post">
      {{render_form(form)}}
      </form>

    <p class="space-above"><a href="{{url_for('cafes')}}">See all cafes</a></p>

    </div>
  </div>
</div>

{% endblock %}

-------------cafes.html

{% extends 'base.html' %}
{% block title %}Restaurants{% endblock %}


{% block content %}

<div class="container">
  <div class="row">
    <div class="col-sm-12">

      <h1>All Cafes</h1>

    <table class="table table-dark table-striped table-hover">
          <!-- This is where you will write the code to render a Bootstrap
          Table that contains all the information from the
          cafe-data.csv file. -->

          <tbody>
            {% for row in data %}
              <tr>
                <td>{{ row[0] }}</td>
                {% if row[1] !='Location' %}
                <td><a href="{{ row[1] }}">Map_link</a></td>  
                {% elif row[1] == 'Location' %}  
                <td>{{row[1]}}</td>
                <!-- Repeat for additional columns -->
                {% endif %}
              </tr>
            {% endfor %}
          </tbody>
      </table>

      <p><a href="{{url_for('home')}}">回 首 頁</a></p>

    </div>
  </div>
</div>

{% endblock %}


-------------style.css

/* to override Bootstrap styles for some things */

body {
background-color: #333;
color: white;
}

a {
    color: #ffc107;
}

.jumbotron {
  display: flex;
  align-items: center;
  margin: 0;
  height: 100vh;
  color: white;
  background-color: #333;
}

.space-above {
    margin-top: 20px;
    padding-top: 20px;
}

-------------------------------------ASNER------------

----------base.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />

    {% block styles %}
    <!-- Load Bootstrap-Flask CSS here -->
    {{ bootstrap.load_css() }}
    <!-- Link to the styles.css here to apply styling to all the child templates.-->
    <link
      rel="stylesheet"
      href="{{ url_for('static', filename='css/styles.css') }}"
    />
    {% endblock %}

    <title>{% block title %}{% endblock %}</title>
  </head>
  <body>
    {% block content %}{% endblock %}
  </body>
</html>


----index.html

{% extends 'base.html' %}
{% block title %}Coffee and Wifi{% endblock %}

{% block content %}
<div class="jumbotron text-center">
  <div class="container">
    <h1 class="display-4">☕️ Coffee & Wifi 💻</h1>
    <p class="lead">Want to work in a cafe but need power and wifi?</p>
    <hr class="my-4" />
    <p>
      You've found the right place! Checkout my collection of cafes with data on
      power socket availability, wifi speed and coffee quality.
    </p>
    <a
      class="btn btn-warning btn-lg"
      href="{{ url_for('cafes') }}"
      role="button"
      >Show Me!</a
    >
  </div>
</div>

{% endblock %}

------------------cafes.html

{% extends 'base.html' %}
{% block title %}All Cafes{% endblock %}

{% block content %}
<div class="container">
  <div class="row">
    <div class="col-sm-12">
      <h1>All Cafes</h1>

      <table class="table" style="color: white">
        {% for row in cafes %}
        <tr>
          {% for item in row %} {% if item[0:4] == "http" %}
          <td><a href="{{ item }}">Maps Link</a></td>
          {% else %}
          <td>{{ item }}</td>
          {% endif %} {% endfor %}
        </tr>
        {% endfor %}
      </table>
      <p><a href="{{ url_for('home') }}">Return to index page</a></p>
    </div>
  </div>
</div>

{% endblock %}


---add.html

{% extends 'base.html' %}
{% from 'bootstrap5/form.html' import render_form %}

{% block title %}Add A New Cafe{% endblock %}
{% block content %}
<div class="container">
  <div class="row">
    <div class="col-sm-12 col-md-8">
      <h1>Add a new cafe into the database</h1>

      {{ render_form(form, novalidate=True) }}

      <p class="space-above">
        <a href="{{ url_for('cafes') }}">See all cafes</a>
      </p>
    </div>
  </div>
</div>

{% endblock %}

------main.py

from flask import Flask, render_template, redirect, url_for
from flask_bootstrap import Bootstrap5
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, SelectField
from wtforms.validators import DataRequired, URL
import csv

'''
Red underlines? Install the required packages first:
Open the Terminal in PyCharm (bottom left).

On Windows type:
python -m pip install -r requirements.txt

On MacOS type:
pip3 install -r requirements.txt

This will install the packages from requirements.txt for this project.
'''

app = Flask(__name__)
app.config['SECRET_KEY'] = '8BYkEfBA6O6donzWlSihBXox7C0sKR6b'
Bootstrap5(app)


class CafeForm(FlaskForm):
    cafe = StringField('Cafe name', validators=[DataRequired()])
    location = StringField("Cafe Location on Google Maps (URL)", validators=[DataRequired(), URL()])
    open = StringField("Opening Time e.g. 8AM", validators=[DataRequired()])
    close = StringField("Closing Time e.g. 5:30PM", validators=[DataRequired()])
    coffee_rating = SelectField("Coffee Rating", choices=["☕️", "☕☕", "☕☕☕", "☕☕☕☕", "☕☕☕☕☕"], validators=[DataRequired()])
    wifi_rating = SelectField("Wifi Strength Rating", choices=["✘", "💪", "💪💪", "💪💪💪", "💪💪💪💪", "💪💪💪💪💪"], validators=[DataRequired()])
    power_rating = SelectField("Power Socket Availability", choices=["✘", "🔌", "🔌🔌", "🔌🔌🔌", "🔌🔌🔌🔌", "🔌🔌🔌🔌🔌"], validators=[DataRequired()])
    submit = SubmitField('Submit')


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


@app.route('/add', methods=["GET", "POST"])
def add_cafe():
    form = CafeForm()
    if form.validate_on_submit():
        with open("cafe-data.csv", mode="a", encoding='utf-8') as csv_file:
            csv_file.write(f"\n{form.cafe.data},"
                           f"{form.location.data},"
                           f"{form.open.data},"
                           f"{form.close.data},"
                           f"{form.coffee_rating.data},"
                           f"{form.wifi_rating.data},"
                           f"{form.power_rating.data}")
        return redirect(url_for('cafes'))
    return render_template('add.html', form=form)


@app.route('/cafes')
def cafes():
    with open('cafe-data.csv', newline='', encoding='utf-8') as csv_file:
        csv_data = csv.reader(csv_file, delimiter=',')
        list_of_rows = []
        for row in csv_data:
            list_of_rows.append(row)
    return render_template('cafes.html', cafes=list_of_rows)


if __name__ == '__main__':
    app.run(debug=True, port=5002)


標籤: ,

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁