DEVELOP
article thumbnail

 

온라인 서비스로 Flask 개발환경 세팅하기

https://glitch.com/edit/#!/resilient-tricky-oak?path=server.py%3A8%3A0 에 접속 

 

Glitch Code Editor ・゚✧

Simple, powerful, free tools to create and use millions of apps.

glitch.com

- Remix 버튼 클릭해서 개발환경 복제하기 

- 하단 Preview - Open previwq pane 클릭해 웹 화면의 결과 확인 가능


Flask의 라우팅 

- 어떤 프레임워크를 사용할지라도 라우팅이 가장 첫번째로 이루어져야하고 가장 중요함

- https://www.geeksforgeeks.org/flask-app-routing/ 참고

- 변수를 URL로 사용하고 싶으면 < > 안에 변수이름을 지정해주고, 그 변수를 함수의 파라미터로 지정해 사용 

from flask import Flask
import random
app = Flask(__name__)

@app.route('/')
def index():
    return 'Welcome!'
  
@app.route('/create/')
def create():
  return 'Create'

@app.route('/read/<id>')
def read(id):
  return 'Read '+id

app.run()

읽기 기능 구현 (Read)

from flask import Flask
import random
app = Flask(__name__)

topics = [
    {'id': 1, 'title': 'html', 'body': 'html is..'},
    {'id': 2, 'title': 'css', 'body': 'css is..'},
    {'id': 3, 'title': 'java', 'body': 'java is..'}
]
def template(article, id=None):
  liTags =''
  for t in topics:
    liTags=liTags + f'''<li><a href="/read/{t["id"]}">{t["title"]}</a></li>'''
  
  return f'''<!doctype html>
    <html>
      <body>
        <h1><a href="/">WEB</a></h1>
          <ol>
            {liTags}
          </ol>
          {article}
      </body>
    </html>
    
    '''
@app.route('/')
def index():
  article = '''
  <h2>Welcome</h2>
  Hello World!
  '''
  return template(article)

@app.route('/read/<id>')
def read(id):
  article =''
  for t in topics:
    if id == str(t["id"]):
      article = f'''
        <h2>{t["title"]}</h2>
        <p>{t["body"]}</p>
      '''
  return template(article)

@app.route('/create/')
def create():
  return 'Create'



app.run()


쓰기 기능 구현 (Create)

from flask import Flask, request, redirect
import random
app = Flask(__name__)

topics = [
    {'id': 1, 'title': 'HTML', 'body': 'HTML is..'},
    {'id': 2, 'title': 'CSS', 'body': 'CSS is..'},
    {'id': 3, 'title': 'JavaScript', 'body': 'JavaScript is..'}
]
def template(article, id=None):
  liTags =''
  for t in topics:
    liTags=liTags + f'''<li><a href="/read/{t["id"]}">{t["title"]}</a></li>'''
  
  context = ''
  if id!= None:
    context = '''
    <ul>
    <li><a href="/create/">Create</a></li>
    </ul>
    '''
    
  return f'''<!doctype html>
    <html>
      <body>
        <h1><a href="/">WEB</a></h1>
          <ol>
            {liTags}
          </ol>
          {article}
          {context}
      </body>
    </html>
    
    '''
@app.route('/')
def index():
  article = '''
  <h2>Welcome</h2>
  Hello World!
  '''
  return template(article)

@app.route('/read/<id>')
def read(id):
  article =''
  for t in topics:
    if id == str(t["id"]):
      article = f'''
        <h2>{t["title"]}</h2>
        <p>{t["body"]}</p>
      '''
  return template(article,id)

@app.route('/create/', methods=['GET','POST'])
def create():
  if request.method == 'GET':
    article = '''
    <form action="/create/" method="post">
      <p><input type="text" name="title" placeholder="title"></p>
      <p><textarea name="body" placeholder="body" rows=6></textarea></p>
      <p><input type="submit" value="create"></p>
    </form>
    '''
    return template(article)
  elif request.method == 'POST':
    title = request.form["title"]
    body = request.form["body"]
    newTopic = {'id':len(topics)+1, 'title':title, 'body':body}
    topics.append(newTopic)
    url = '/read/'+str(len(topics))
    return redirect(url)


app.run()


수정 기능 구현 (Update)

from flask import Flask, request, redirect
import random
app = Flask(__name__)

topics = [
    {'id': 1, 'title': 'HTML', 'body': 'HTML is..'},
    {'id': 2, 'title': 'CSS', 'body': 'CSS is..'},
    {'id': 3, 'title': 'JavaScript', 'body': 'JavaScript is..'}
]
def template(article, id=None):
  liTags =''
  for t in topics:
    liTags=liTags + f'''<li><a href="/read/{t["id"]}">{t["title"]}</a></li>'''
  
  context = ''
  if id!= None:
    context = f'''
    <li><a href="/update/{id}">Update</a></li>
    '''
    
  return f'''<!doctype html>
    <html>
      <body>
        <h1><a href="/">WEB</a></h1>
          <ol>
            {liTags}
          </ol>
          {article}
          <ul>
            <li><a href="/create/">Create</a></li>
            {context}
          </ul>
      </body>
    </html>
    
    '''
@app.route('/')
def index():
  article = '''
  <h2>Welcome</h2>
  Hello World!
  '''
  return template(article)

@app.route('/read/<id>')
def read(id):
  article =''
  for t in topics:
    if id == str(t["id"]):
      article = f'''
        <h2>{t["title"]}</h2>
        <p>{t["body"]}</p>
      '''
      break
  return template(article,id)

@app.route('/create/', methods=['GET','POST'])
def create():
  if request.method == 'GET':
    article = '''
    <form action="/create/" method="post">
      <p><input type="text" name="title" placeholder="title"></p>
      <p><textarea name="body" placeholder="body" rows=6></textarea></p>
      <p><input type="submit" value="create"></p>
    </form>
    '''
    return template(article)
  elif request.method == 'POST':
    title = request.form["title"]
    body = request.form["body"]
    newTopic = {'id':len(topics)+1, 'title':title, 'body':body}
    topics.append(newTopic)
    url = '/read/'+str(len(topics))
    return redirect(url)

@app.route('/update/<id>', methods=['GET','POST'])
def update(id):
  for t in topics:
    if id == str(t["id"]):
      selectTitle = t["title"]
      selectBody = t["body"]
      break
  if request.method == 'GET':
    article = f'''
    <form action="/update/{id}" method="post">
      <p><input type="text" name="title" value={selectTitle}></p>
      <p><textarea name="body" rows=6>{selectBody}</textarea></p>
      <p><input type="submit" value="update"></p>
    </form>
    '''
    return template(article)
  elif request.method == 'POST':
    title = request.form["title"]
    body = request.form["body"]
    newTopics = []
    for t in topics : 
      if id == str(t["id"]):
        t["title"] = title
        t["body"] = body
        break
    url = '/read/'+ id
    return redirect(url)

app.run()

 


삭제 기능 구현 (Delete)

from flask import Flask, request, redirect
import random
app = Flask(__name__)

topics = [
    {'id': 1, 'title': 'HTML', 'body': 'HTML is..'},
    {'id': 2, 'title': 'CSS', 'body': 'CSS is..'},
    {'id': 3, 'title': 'JavaScript', 'body': 'JavaScript is..'}
]
def template(article, id=None):
  liTags =''
  for t in topics:
    liTags=liTags + f'''<li><a href="/read/{t["id"]}">{t["title"]}</a></li>'''
  
  context = ''
  if id!= None:
    context = f'''
    <li><a href="/update/{id}">Update</a></li>
    <form action="/delete/{id}" method="post">
      <li><input type="submit" value="delete"></li>
    </form>
    '''
    
  return f'''<!doctype html>
    <html>
      <body>
        <h1><a href="/">WEB</a></h1>
          <ol>
            {liTags}
          </ol>
          {article}
          <ul>
            <li><a href="/create/">Create</a></li>
            {context}
          </ul>
      </body>
    </html>
    
    '''
@app.route('/')
def index():
  article = '''
  <h2>Welcome</h2>
  Hello World!
  '''
  return template(article)

@app.route('/read/<id>')
def read(id):
  article =''
  for t in topics:
    if id == str(t["id"]):
      article = f'''
        <h2>{t["title"]}</h2>
        <p>{t["body"]}</p>
      '''
      break
  return template(article,id)

@app.route('/create/', methods=['GET','POST'])
def create():
  if request.method == 'GET':
    article = '''
    <form action="/create/" method="post">
      <p><input type="text" name="title" placeholder="title"></p>
      <p><textarea name="body" placeholder="body" rows=6></textarea></p>
      <p><input type="submit" value="create"></p>
    </form>
    '''
    return template(article)
  elif request.method == 'POST':
    title = request.form["title"]
    body = request.form["body"]
    newTopic = {'id':len(topics)+1, 'title':title, 'body':body}
    topics.append(newTopic)
    url = '/read/'+str(len(topics))
    return redirect(url)

@app.route('/update/<id>', methods=['GET','POST'])
def update(id):
  for t in topics:
    if id == str(t["id"]):
      selectTitle = t["title"]
      selectBody = t["body"]
      break
  if request.method == 'GET':
    article = f'''
    <form action="/update/{id}" method="post">
      <p><input type="text" name="title" value={selectTitle}></p>
      <p><textarea name="body" rows=6>{selectBody}</textarea></p>
      <p><input type="submit" value="update"></p>
    </form>
    '''
    return template(article)
  elif request.method == 'POST':
    title = request.form["title"]
    body = request.form["body"]
    newTopics = []
    for t in topics : 
      if id == str(t["id"]):
        t["title"] = title
        t["body"] = body
        break
    url = '/read/'+ id
    return redirect(url)

@app.route('/delete/<id>', methods=['POST'])
def delete(id):
  for t in topics:
    if id == str(t["id"]):
      topics.remove(t)
      break
  return redirect('/')

app.run()

 

'STUDY > Python' 카테고리의 다른 글

[ 생활코딩 - Web2 Python ] Django Framework - CRUD 구현  (0) 2022.12.13
profile

DEVELOP

@JUNGY00N