Day 060

AWESOMee·2022년 4월 8일
0

Udemy Python Bootcamp

목록 보기
60/64
post-thumbnail

Udemy Python Bootcamp Day 060

Make POST Requests with Flask and HTML Forms

HTML Forms Revision - Creating a Form from Scratch

from flask import Flask, render_template

app = Flask(__name__)


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


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

<form>
  <h1>It works!</h1>
  <hr>
  <label>Name</label>
  <input type="text" placeholder="name">
  <label>Password</label>
  <input type="password" placeholder="password">
  <button type="submit">Ok</button>
</form>


Handle POST Requests with Flask Servers

<form action="/login" method="post">

from flask import request

@app.route('/login', methods=["POST"])
def receive_data():
    name = request.form['username']
    password = request.form['password']
    return f"<h1>Name: {name}, Password: {password}</h1>"


Getting the Contact Form to Work

<form name="sentMessage" action="{{ url_for('receive_data') }}" id="contactForm" method="post">

and add name attribute to input

from flask import request

@app.route('/form-entry', methods=["POST"])
def receive_data():
    data = request.form
    print(data["name"])
    print(data["email"])
    print(data["phone"])
    print(data["message"])
    return "<h1>Successfully sent your message</h1>"

data[]인데 ()로 입력해서 한참을 헤맸다..


<form name="sentMessage" action="{{ url_for('contact') }}" id="contactForm" method="post">

<form> action updated to contact

@app.route('/contact', methods=["GET", "POST"])
def contact():
    if request.method == 'POST':
        data = request.form
        print(data["name"])
        print(data["email"])
        print(data["phone"])
        print(data["message"])
        return "<h1>Successfully sent your message</h1>"
    return render_template('contact.html')



<div class="page-heading">
  {% if msg_sent: %}
  <h1>Successfully sent your message</h1>
  {% else: %}
  <h1>Contact Me</h1>
  {% endif %}
  <span class="subheading">Have questions? I have answers.</span>
</div>

Instead of returning a <h1> that says "Successfully sent message", update the contact.html file so that the <h1> on the contact.html file becomes "Successfully sent message".

@app.route('/contact', methods=["GET", "POST"])
def contact():
    if request.method == 'POST':
        data = request.form
        print(data["name"])
        print(data["email"])
        print(data["phone"])
        print(data["message"])
        return render_template('contact.html', msg_sent=True)
    return render_template('contact.html', msg_sent=False)

after sent the message


Sending Email with smtplib

import smtplib

my_email = "************@yahoo.com"
password = "*************"

@app.route('/contact', methods=["GET", "POST"])
def contact():
    if request.method == 'POST':
        data = request.form
        with smtplib.SMTP("smtp.mail.yahoo.com") as connection:
            connection.starttls()
            connection.login(user=my_email, password=password)
            connection.sendmail(
                from_addr=my_email,
                to_addrs="***********@gmail.com",
                msg=f"Subject:New Message\n\n"
                    f"Name: {data['name']}\n"
                    f"Email: {data['email']}\n"
                    f"Phone: {data['phone']}\n"
                    f"Massage: {data['message']}"
            )
        return render_template('contact.html', msg_sent=True)
    return render_template('contact.html', msg_sent=False)


Solution은 class로 작성함

@app.route('/contact', methods=["GET", "POST"])
def contact():
    if request.method == 'POST':
        data = request.form
        send_email(data["name"], data["email"], data["phone"], data["message"])
        return render_template('contact.html', msg_sent=True)
    return render_template('contact.html', msg_sent=False)


def send_email(name, email, phone, message):
    email_message = f"Subject:New Message\n\nName: {name}\nEmail: {email}\nPhone: {phone}\nMassage: {message}"
    with smtplib.SMTP("smtp.mail.yahoo.com") as connection:
        connection.starttls()
        connection.login(my_email, password)
        connection.sendmail(my_email, "***********@gmail.com", email_message)

FINAL

from flask import Flask, render_template, request
import requests
import smtplib

my_email = "***********@yahoo.com"
password = "***********"

posts = requests.get("https://api.npoint.io/2b75de17c055f76690b5").json()

app = Flask(__name__)


@app.route('/')
def get_all_posts():
    return render_template('index.html', all_posts=posts)


@app.route('/post/<int:index>')
def post(index):
    requested_post = None
    for blog_post in posts:
        if blog_post["id"] == index:
            requested_post = blog_post
    return render_template('post.html', post=requested_post)


@app.route('/about')
def about():
    return render_template('about.html')


@app.route('/contact', methods=["GET", "POST"])
def contact():
    if request.method == 'POST':
        data = request.form
        send_email(data["name"], data["email"], data["phone"], data["message"])
        return render_template('contact.html', msg_sent=True)
    return render_template('contact.html', msg_sent=False)


def send_email(name, email, phone, message):
    email_message = f"Subject:New Message\n\nName: {name}\nEmail: {email}\nPhone: {phone}\nMassage: {message}"
    with smtplib.SMTP("smtp.mail.yahoo.com") as connection:
        connection.starttls()
        connection.login(my_email, password)
        connection.sendmail(my_email, "***********@gmail.com", email_message)


if __name__ == "__main__":
    app.run(debug=True)
profile
개발을 배우는 듯 하면서도

0개의 댓글