WEB

Replit으로 flask 실습해보기

with_AI 2022. 4. 6. 16:17

Replit에 일단 로그인, 접속을 한다.

 

flask는 다음과 같은 web 아키텍처중에

application sever 단의 작업이다.

 

 

https://replit.com/~

 

Log In

Replit is a simple yet powerful online IDE, Editor, Compiler, Interpreter, and REPL. Code, compile, run, and host in 50+ programming languages.

replit.com

 

접속을 하고 파이썬으로 접속하면 다음과 같은 창이 나온다.

 

 

 

pip install flask를 해야 합니다. 하지 않으면 import 가 되지 않습니다.

shell에서 flask 설치 후 위와 같은 코드를 치면 console창에서 결과가 나오는것을 확인 가능합니다.

 

 

 

이번에는 route를 더 추가해서 사이트에서 경로를 더 만들어보자

routing : 사용자의 접속 경로를 지정하는 것

 

 

posts 라우터와, todos 라우터에 각각 잘 출력이 잘 되는 모습을 볼 수 있다.

 

 

 

이제는 json 예제 api를 가져와서 json으로 출력해보자

예제 사이트 : https://jsonplaceholder.typicode.com/posts

 

 

requests, jsonify 라이브러리를 가져와서 posts 라우터의 코드를 수정했다.

response 객체에 requests.get으로 api를 호출하고 리턴을 받아서

to_serve 변수에 response 객체를 json으로 변환하여 저장한다.

 

그리고 flask에서는 jsonify를 활용하여 return 해줘야 정상적으로 출력이 된다.

다음과 같이 코드를 작성하게 되면 posts 라우터에 접속시 json데이터가 출력되는 것을 확인할 수 있다.

 

 

다음에는 templates라는 폴더를 만들고 그 폴더 안에 index.html 파일을 다음과 같이 생성한다.

그리고 render_template를 사용하여 index함수의 return 값으로 render_template('index.html')로 templates 폴더 안에 있는 index.html 파일을 랜더링시킨다.

 

 

 

 

다음은 string을 받아서 받은 스트링을 렌더링 해주는 라우팅을 만들어보자.

 

다음과 같이 quote/<string>:name 이라는 라우터를 선언했는데, quote 밑에 string이 name으로 되는 경로를 설정했다.

이제 name 을 아무렇게 주어면, This is quote (name)이 렌더링 된다.

 

 

최종 코드

from flask import Flask, jsonify, render_template
import requests

app = Flask(__name__)

@app.route('/') #데코레이터
def index():
  return render_template('index.html')

@app.route('/posts')
def show_posts():
  response = requests.get("https://jsonplaceholder.typicode.com/posts")
  to_serve = response.json()
  return jsonify(to_serve)

@app.route('/todos')
def show_todos():
  return "todos"

@app.route('/quote/<string:name>')
def show_quote(name = None):
  return "This is quote {}".format(name)

if __name__=='__main__':
  app.run(host='0.0.0.0', port = 5000, debug=True)

 

 

 

'WEB' 카테고리의 다른 글

JS 기본 문법  (0) 2022.04.12
HTML 실습  (0) 2022.04.11
WEB 개발 환경 필수 프로그램 설치  (0) 2022.04.11
API  (0) 2022.04.06
WEB 개발의 기초  (0) 2022.04.06