티스토리 뷰

Python

Flask app: cafe_api

daylee de vel 2021. 7. 5. 20:25

유데미 파이썬 강의 Flask: Restful API 복습

Section 66: Day 66 - Advanced - Building Your Own API with RESTful Routing 

set FLASK_APP=mian.py
set FLASK_ENV=development
(한번 지정해 놓으면 계속 사용가능)

서버 시작
flask run 
서버 연결 끊기
ctrl + c

route("/random", methods=["GET"])

Normally, we've been returning HTML templates using render_template(), but this time, because our server is now acting as an API, we want to return a JSON containing the necessary data. Just like real public APIs.

지금까지는 HTML 템플릿을 리턴해줬지만, 이번에는 서버가 API로 이용되기 때문에 데이터를 JSON 형식으로 돌려줄 것임. 

In order to do this, we have to turn our random_cafe SQLAlchemy Object into a JSON. This process is called serialization. Flask has a serialisation helper method built-in called jsonify() . But we have to provide the structure of the JSON to return.

Serialization

SQLALchemy 객체를 JSON으로 바꿔주는 것. 플라스크에는 serialization을 도와주는 jsonify() 함수가 내장되어 있음. 

But in most cases, you might just want to return all the data you have on a particular record and it would drive you crazy if you had to write out all that code for every route. 아래처럼 모든 라우트에 일일이 key-value 형식을 적어주기 어렵기 때문에

@app.route("/random")
def get_random_cafe():
    cafes = db.session.query(Cafe).all()
    random_cafe = random.choice(cafes)

    return jsonify(
        cafe={
        "name" : random_cafe.name,
        "map_url" : random_cafe.map_url,
        "img_url" : random_cafe.img_url,
        "location" : random_cafe.location,
        "seats" : random_cafe.seats,
        "has_toilet" : random_cafe.has_toilet,
        "has_wifi" : random_cafe.has_wifi,
        "has_sockets" : random_cafe.has_sockets,
        "can_take_calls" : random_cafe.can_take_calls,
        "coffee_price" : random_cafe.coffee_price
    })

So another method of serialising our database row Object to JSON is by first converting it to a dictionary and then using jsonify() to convert the dictionary (which is very similar in structure to JSON) to a JSON.

serialisation을 하는 다른 방식은 DB 열(row) 객체를 dictionary형식으로 바꾼 뒤, jsonify를 이용해 dicitonary를 JSON으로 바꿀 수 있다. 

class Cafe(db.Model):
    id = db.Column(db.Integer, primary_key=True)

    def to_dict(self):
        # Method 1.
        dictionary = {}
        # Loop through each column in the data record
        for column in self.__table__.columns:
            # Create a new dictionary entry;
            # where the key is the name of the column
            # and the value is the value of the column
            dictionary[column.name] = getattr(self, column.name)
        return dictionary
        # Method 2. Altenatively use Dictionary Comprehension to do the same thing.
        # return {column.name: getattr(self, column.name) for column in self.__table__.columns}

 

jsonify로 받은 데이터를 보기 쉽게 포맷팅하기

이슈:

한줄로 데이터를 보여줘서 디버그 하기 어렵다.

솔루션

 prettyprint를 적용하기 위해서는 JSONIFY_PRETTYPRINT_REGULAR 을 False 에서 True로 바꿔줘야한다.

if __name__ == '__main__':
    app.run(debug=True)
    app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True

서버를 시작할 때 다음과 같이 시작해야함

set FLASK_ENV=development
flask run

 

debug 디버그 모드 켜기

이슈
아래와 같이 서버를 시작하면 디버그 모드가 off 됨

코드를 수정할 때 마다 리프레시하려면 ctrl+c로 서버를 껐다 켜야했음

set FLASK_APP=main.py
flask run

 

솔루션

main.py

debug=True로 설정 확인 후 

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

터미널에서 아래 입력 후 PIN 넘버를 입력해 줘야 함.

자동으로 리프레시가 되어 서버를 on off 하지 않아도 됨.

set FLASK_ENV=development
flask run

 

Flask SQLAlchemy ORM 

SQL 쿼리 대신 ORM을 사용하여 데이터베이스를 CURD 할 수 있습니다.

https://lowelllll.github.io/til/2019/04/19/TIL-flask-sqlalchemy-orm/

 

POSTMAN 사용

1. POSTMAN 데스크탑 버젼에서 BOOTCAMP 기능을 적극 활용하기!

콜렉션을 만들면 Method 추가하며 테스트 할 수 있음

콜렉션 단위로 API document를 자동생성해줌

'Python' 카테고리의 다른 글

Flask app: RESTful-blog  (0) 2021.07.07
Flight Deal  (0) 2021.06.21
TIL Python Basics Day 30 - Errors, Exceptions and JSON Data  (0) 2021.06.17
파이썬 복습: Computational thinking  (1) 2021.06.10
Udemy Python Pro Bootcamp by Angela Yu  (0) 2021.06.07
댓글