#docker #kubernetes #container #orchestrator #microservice #infrastructure-as-code #devops #ci #cd

제목[Q&A] Python, Flask로 간단한 웹 서버 짜기(Flask의 여러 가지 기능)2019-12-12 10:06
작성자

Flask를 통한 웹개발도 생각보다 여러가지 찾아봐야 하더군요. 그래서 이 수업에서 필요했던 것만 모아봤습니다.


1. 웹 경로에 따른 html 보내기

from flask import Flask

app = Flask(__name__)

host = "0.0.0.0"
port = 8080

@app.route('/')
def index() :
html =
"<h1>search 서버입니다.</h1>"
"<h3>API</h3>"
"<p>/booksearch"
"<li>param: title(string)</li></p>"
return html

if __name__ == "__main__" :
app.run(host=host, port=port, debug=False)

우선 가장 기본이 되는 '/' 경로의 출력을 지정하는 방법입니다. html 텍스트를 직접 써서 반환하고 있습니다.

웹 서버를 실행할 때는 app.run 함수를 씁니다. 위 예시에서는 "localhost:8080/"으로 접속하면 html을 확인할 수 있습니다.

from flask import Flask, render_template
...
@app.route('/')
def index(): return render_template('index.html')
...
이렇게 .html 파일을 반환할 수도 있습니다.

...
@app.route
('/booksearch')
def booksearch() :
html =
"<h1>search 서버입니다.</h1>"
"<h3>API</h3>"
"<p>/booksearch"
"<li>param: title(string)</li></p>"
return html
...
위와 같이 @app.route(경로) 형태로 특정 웹 경로에서 반환할 내용을 지정해 줄 수 있습니다.
위의 예시에서는 'localhost:8080/booksearch' 경로에서 보여줄 내용을 정의하고 있습니다.

2. 웹 경로로 변수 받기

...
@app.route("/month/url/<year_month>")
def month_url(year_month) :
namu_url = c.get_year_month_url(year_month)
html = "<a href={0}>{1}</a>"
return html.format(namu_url, year_month)
...
경로를 지정할 때 <변수 이름> 형식으로 매개 변수를 넣어서 이용하는 것도 가능합니다.
'localhost:8080/month/url/2017-12'로 접속하면 정의한 함수에서 year_month 변수에 '2017-12'가 들어갔을 때의 html을 반환받습니다.

3. Restful api 만들기


http에는 단순히 html을 돌려주는 기능만 하지 않습니다.
Get, Post, Delete 등의 http 함수를 써서 json이나 xml을 통해 정보를 주고받는 api로서의 기능도 수행합니다. 이를 RestFul API라고 합니다.
Flask를 써서도 이와 같은 기능을 수행할 수 있습니다. 단, Flask와는 별개인 flask_restful 모듈을 설치해야 합니다.
from flask import Flask
from flask_restful import Resource, Api, reqparse
...
app = Flask(__name__)
api = Api(app)
...
class GetAccuracy(Resource):
def get(self):
try:
json_dict = {
"result": "결과입니다."
}
return json_dict
except Exception as e:
return {'error': str(e)}

api.add_resource(GetAccuracy, '/nlp/accuracy/title')
...

Flask에서는 Restful api를 class를 써서 구현합니다.

class의 멤버 변수는 Restful api의 함수를 의미합니다. 예시에서 정의하고 있는 'get' 함수 외에도 'post', 'put', 'delete' 등의 함수를 필요에 따라 정의할 수 있습니다.

또 이렇게 정의한 클래스를 add_resource 함수로 웹 경로와 함께 등록합니다.

위 예시에서는 'localhost:8080/nlp/accuracy/title'로 GET 요청을 보내면 "result" 키에 "결과입니다." 값이 등록돼 있는 JSON이 반환됩니다.


4. Restful API에 보내는 매개변수

Restful API에는 매개변수가 있습니다. api를 부를 때 웹 경로 뒤에 ?와 함께 붙는 '?<변수 이름>=<변수 값>&<변수 이름>=<변수 값>...'하는 형식으로 이어지는 것들입니다.

Flask에서도 매개변수를 받을 수 있습니다.

...
class GetAccuracy(Resource):
def get(self):
        try:
            parser = reqparse.RequestParser()
            parser.add_argument('ori_title', required=True, type=str, help='ori_title cannot be blank')
            parser.add_argument('searched_title', required=True, type=str, help='searched_title cannot be blank')
            args = parser.parse_args()

            json_dict = {
                "result": nlp_module.search_accsuracy_examine(args['ori_title'], args['searched_title'])
            }
            return json_dict
        except Exception as e:
            return {'error': str(e)}
api.add_resource(GetAccuracy, '/nlp/accuracy/title')
...

flask_restful의 reqparse 모듈 안에 있는 RequestParser 클래스로 매개변수를 받을 수 있습니다. add_argumet 함수를 통해 추가할 수 있으며 변수의 이름, 필수 여부 등을 지정할 수 있습니다.

위 예시에서는 'localhost:8080/nlp/accuracy/title?ori_title=약사의 혼잣말&searched_title=약사의 혼잣말1' 형식으로 GET 요청을 보내 JSON을 받아오게 됩니다.

이상입니다.


#python#flask#restful
댓글