TIL Python Basics Day 62 - Coffee & Wifi Project: Flask, WTForms, Bootstrap and CSV

이다연·2021년 2월 20일
0

Udemy Python Course

목록 보기
58/64

It has been really difficult since the module became ADVANCED LEVEL.
Following the lesson only by reading official docs didn't work. I googled another tutorial to guide me through the topic. This is what the instructor intended, to save us from tutorial hell. I googled the right article, It provided the very detailed explanation. I understood each lines of code, instead of copying and pasting.

  • Official documents only works when I have a base knowledge. Just browse and get the keyword from docs and google it for step by step tutorials!
  • Since this module became advanced level, I got headache every night. It was so difficult and I felt very frustrated. -> Having enough resting, break time is important. Don't feel overwhemed and blame yourself. Next day with fresh eyes and brain, everything clicked. Find the balance between focus time and break.

CSS path

href="{{ url_for('static', filename='css/styles.css') }}

{% block styles %}
{{super()}}
	<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
{% endblock %}

Field

Notice the format for each field type

from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, SelectField
from wtforms.validators import DataRequired, URL

class CafeForm(FlaskForm):
    name = StringField('Cafe Name', validators=[DataRequired()])
    location = StringField('Location',
                                validators=[DataRequired(),
                                            URL(message=('Not a valid URL.'))])  


    open = SelectField('Open',
                                validators=[DataRequired()],
                                choices=[ 
                                    '9 A.M',
                                    '5 P.M'
                                ])

    coffee = SelectField('Coffee',
                                validators=[DataRequired()],
                                choices=[
                                    '☕',
                                    '☕☕',
                                    '☕☕☕',
                                    '☕☕☕☕',
                                    '☕☕☕☕☕'])

Bootstrap Table: For Loop

You're aiming for a table-row (<tr>) per user, 
  and some table-data (<td>) for each of their attributes. 

csv file

cafes [list]
[['Cafe Name', 'Location', 'Open', 'Close', 'Coffee', 'Wifi', 'Power'],
  ['Lighthaus', 'https://goo.gl/maps/2EvhB4oq4gyUXKXx9', '11AM', ' 3:30PM', '☕☕',.,]]
<table class="table">

	  {% 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>

CSV file

UnicodeDecodeError: 'utf8' codec can't decode byte 0x9c

with open( encoding='utf-8')
        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.data},"
                           f"{form.wifi.data},"
                           f"{form.power.data}")

Result


@app.route('/add', methods=["GET", "POST"])
def add_cafe():
    form = CafeForm()
    """ POST: Get hold of form data input by user, save them into csv file"""
    if form.validate_on_submit():
        with open("cafe-data.csv", mode="a") 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'))
    """ GET: show empty form to fill in """
  	return render_template('add.html', form=form)


@app.route('/cafes')
def cafes():
    with open('cafe-data.csv', newline='') 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)

Index

Add a Cafe

Cafe List

profile
Dayeon Lee | Django & Python Web Developer

0개의 댓글