본문 바로가기

Programming/Python

웹서버를 사용하기 위해 어떤 프레임워크를 고를 것인가?

 파이썬 웹 프레임 워크를 고르는 것.


웹서버 하나 작은걸 만들어 보려고 교재를 찾아보던 중에,  Django 와 Flask 두가지를 이용한 설명이 많았는데, 어느것으로 만들지 고민하다가 찾은 글이다. 

https://www.airpair.com/python/posts/django-flask-pyramid

보다보니 제대로 읽어보고픈 마음에 글로 해석을 시작했다. 


만만하게 보고 해석 달아보려고 시도했는데 벌써 두시간도 넘어간다 ㅠㅠ 게다가 나의 영어 실력에도 한계를 느끼는 중. 

나머지 못한 부분은 다음에 이어서...







Django vs Flask vs Pyramid: Choosing a Python Web Frameworks

Ryan works on Openstack Heat at Red Hat and has written Python for web, orchestration, and backend applications large and small.

1 Introduction

The world of Python web frameworks is full of choices. Django, Flask, Pyramid, Tornado, Bottle, Diesel, Pecan, Falcon, and many more are competing for developer mindshare. As a developer you want to cut the legions of options down to the one that will help you finish your project and get on to the Next Big Thing (tm). We'll focus on Flask, Pyramid, and Django. Their ideal cases span from micro-project to enterprise-size web service.

파이썬 웹 프레임워크의 세상에는 선택들이 엄청 많다. 장고, 플라스크, 피라미드, 토네이도, 보틀, 디젤, 페칸, 팔콘, 게다가 더 많은 것들이 개발자들의 마음을 뺫기 위해 경쟁중이다. 개발자로써 당신은 이런 수많은 옵션들을 좀 쳐내고, 당신의 프로젝트를 끝마치고, 다음 위대한 프로젝트로 이동하도록 하나를 골라보자. 우리는 플라스크, 피라미드, 장고에 초점을 맞출 것이다. 이것들의 이상적인 경우들을 아주 작은 프로젝트부터, 엄청 큰 프로젝트까지에 걸쳐 알아보자. 


To help make the choice between the three easier (or at least more informed), we'll build the same application in each framework and compare the code, highlighting the strengths and weaknesses of each approach. If you just want the code, skip straight to Frameworks in Action or view the code on Github.

이 세가지중에 선택을 돕기위해, 우리는 같은 오플리케이션을 각각에 프레임워킄에 맞춰 코드를 비교하고, 각각의 장단점이 무엇인지 접근했다. 만약 당신이 바로 소스코드를 보고싶다면, 건너ㄱ뛰고, 깃헙의 링크로 가서 확인하도록. 


Flask is a "microframework" primarily aimed at small applications with simpler requirements. Pyramid and Django are both aimed at larger applications, but take different approaches to extensibility and flexibility. Pyramid targets flexibility and lets the developer use the right tools for their project. This means the developer can choose the database, URL structure, templating style, and more. Django aims to include all the batteries a web application will need so developers need only open the box and start working, pulling in Django's many modules as they go.

플라스크는 엄청작은 프레임워크로써, 작고 간단한 요구를 수용하는데 촛점이 맞추어져있다. 피라미드와 장고는 둘다 커다란 어플을 만드는데 촛점이 있다. 하지만 확장성과, 유연성에 있어서 차이점이 있다. 피라미드는 목표의 유연성에 목표를 두고 있고, 개발자들이 그들의 프로젝트를 위해 제대로된 도구를 사용하도록 한다. 이것은 개발자들이 데이터베이스나, URL구조, 템플릿스타일, 등등을 고를 수 있다는것을 뜻한다. 장고는 모든 웹 어플리케이션이 필요로 하는 모든 배터리를 포함하고 있기 때문에, 그저 그냥 뚜껑을 열고 일을 시작하고, 장고의 많은 모듈에 밀어넣을 수 있다. 


Django includes an ORM out of the box, while Pyramid and Flask leave it to the developer to choose how (or if) they want their data stored. The most popular ORM for non-Django web applications is SQLAlchemy by far, but there are plenty of other options from DynamoDB and MongoDB to simple local persistence like LevelDB or plain SQLite. Pyramid is designed to use any persistence layer, even yet-to-be-invented ones.

망고는 ORM을 포함하고 있다. 피라미드와, 플라스크는 개발자가 어떤식으로 데이터를 저장할지 선택의여지를 남겨둔다. 가장 유명한 비-장고 웹 ORM은 SQLAlchemy지만, 그밖에도, 엄청나게 많은 , DynamoDB부터 MongoDB 를 포함해, 간단한 로컬저장방법인 LevelDB 나 SQLite 같은 옵션이 있다. 피라미드는 어떤 레이어를 선택해도 되고 , 심지어 만들어도 된다. 


2 About the Frameworks

Django's "batteries included" approach makes it easy for developers who know Python already to dive in to web applications quickly without needing to make a lot of decisions about their application's infrastructure ahead of time. Django has for templating, forms, routing, authentication, basic database administration, and more built in. In contrast, Pyramid includes routing and authentication, but templating and database administration require external libraries.

장고의 “배터리 포함되어있음”은 파이썬을 알고 이미 많은 웹 어플리케이션 작업을 시도해 보고 그들의 어플리케이션의 구조를 결정하기 위해 수많은 시간과 결정들을 소모했을 많은 개발자들에게 쉽운 방법이다. 장고는 템플릿화, 폼, 루팅, 권한, 기본적인 데이터베이스를 가지고 있다. 반면에 피라미드는 루팅과, 권한이 있지만, 템플릿화와 데이터베이스는 외부 라이브러리를 필요로 한다. 


 The extra work up front to choose components for Flask and Pyramid apps yields more flexibility for developers whose use case doesn't fit a standard ORM, or who need to interoperate with different workflows or templating systems.

추가적인 부품들을 고르는 일은, 플라스크와 피라미드에서, 표준 ORM에 맞지 않는 케이스나 다른 템플릿에서 동작하는 시스템의 협업이 필요한 케이스에서 개발자들로 하여금 더 많은 유연성을 지니게 된다. 


Flask, the youngest of the three frameworks, started in mid-2010. The Pyramid framework began life in the Pylons project and got the name Pyramid in late 2010, though the first release was in 2005. Django had its first release in 2006, shortly after the Pylons (eventually Pyramid) project began. Pyramid and Django are extremely mature frameworks, and have accumulated plugins and extensions to meet an incredibly large range of needs.

플라사크는 세개중에 가장 최신의 프레임워크로, 2010년 중반에 시작되었다. 피라미드 프레임워크가 파일런 프로젝트로부터 시작되어 2010년 말에 피라미드라는 이름을 얻었지만, 첫번째 릴리즈는 2005년이었다. 장고는 첫 릴리즈를 2006년에 했고, 파일런프로젝트가 시작된 바로 조금 다음이었다. 피라미드와 장고는 굉장히 잘 성숙되었고, 수많은 확장과 플러그인들이 엄청나게 많은 범위에 걸쳐서 축정되고, 만날 수 있다. 


Though Flask has a shorter history, it has been able to learn from frameworks that have come before and has set its sights firmly on small projects. It is clearly used most often in smaller projects with just one or two functions. One such project ishttpbin, a simple (but extremely powerful) helper for debugging and testing HTTP libraries.

플라스크가 더 짧은 역사에도 불구하고, 작은 프로젝트에 있어서 배울 수 있다. 한개나 두개의 기능만을 하는 아주 작은 프로젝트에서 제일 많이 쓰인다는 것은 확실하다. 대표적으로, httpbin 이라는 아주 단순한 HTTP 라이브러리 테스트 및 디버깅 툴 프로젝트에 쓰인다. 


3 Community

The prize for most active community goes to Django with 80,000 StackOverflow questions and a healthy set of blogs from developers and power users. The Flask and Pyramid communities aren't as large, but their communities are quite active on their mailing lists and on IRC. With only 5,000 StackOverflow questions tagged, Flask is 15x smaller than Django. On Github, they have a nearly identical number of stars with 11,300 for Django, and 10,900 for Flask.

가장 커뮤니티가 활성화가 된 곳은 장고로써, 80,000명의 스택오버플로우 질문과, 파워유저들의 양질의 블로그가 있다. 플라스크와 피라미드 커뮤니티들은 그만큼 크지는 않지만, 그들도 꽤 활성화되어 있다. 단 5,000개의 스택오버플로우 질문으로 장고와 비교해서 플라스크는 15배 작다. 깃헙에서는 11,300개의 장고 , 10,900개의 플라스크가 있어 거의 비슷하다. 

All three frameworks are available under BSD-derived permissive licenses. BothFlask's and Django's licenses are 3-clause BSD, while Pyramid's Repoze Public License RPL is a derivative of the 4-clause BSD license.

이 세가지 프레임워크 전부는 BSD에서 파생된 라이센스로 사용 가능하다. 플라스크와 장고는 3-clause BSD 라이센스고, 피라미드의 라이센스는 4-clause BSD 라이센스에서 파생되었다. 


4 Bootstrapping

Django and Pyramid both come with bootstrapping tools built in. Flask includes nothing of the sort because Flask's target audience isn't trying to build large MVCapplications.

장고와 피라미드는 부트스트랩으로 만드는 도구를 지니고 있다. 플라스크는 그런 툴은 없는데, 플라스크의 타겟층은 큰 MVC 어플리케이션을 만드는데 있지 않기 때문이다. 


4.1 Flask

Flask's Hello World app has to be the simplest out there, clocking in at a puny 7 lines of code in a single Python file.

플라스크의 Hello World 앱은 가장 단순하다. 자그마한 7줄의 코드로 구성된 파일 한개이다. 


# from http://flask.pocoo.org/ tutorial

from flask import Flask

app = Flask(__name__)


@app.route("/") # take note of this decorator syntax, it's a common pattern

def hello():

    return "Hello World!"


if __name__ == "__main__":

    app.run()


This is why there aren't bootstrapping tools for Flask: there isn't a demand for them. From the above Hello World featured on Flask's homepage, a developer with no experience building Python web applications can get hacking immediately.

이것이 왜 플라스크에는 부트스트랩용 도구가 없는지를 보여준다. 그것이 필요 없기 때문이다. 위의 Hello World 플라스크의 홈페이지에 따르면, 개발자는 파이썬을 전혀 다뤄 본 적 없는 개발자도 바로 무언가를 만들 수 있다. 


For projects that need more separation between components, Flask has blueprints. For example, you could structure your Flask app with all user-related functions inusers.py and your sales-related functions in ecommerce.py, then import them and add them to your app in site.py. We won't go over this functionality, as it's beyond the needs of our demo app.

프로젝트를 위해 몇가지 구성요소들을 분리할 필요가 있다면, 플라스크는 blueprints가 있다. 예를 들면 당신의 플라스크앱의 유저관련 함수를 전부 users.py에 넣고, 판매 관련 함수들을 ecommerce.py에 넣은 후에, 그것들을 site.py에 추가해서 작동 시키는 방식으로 구성 할 수 있다. 우리의 데모앱의 필요성을 뛰어넘는 기능들로 하지 않는다. (?)


4.2 Pyramid

Pyramid's bootstrapping tool is called pcreate which is part of Pyramid. Previously the Paste suite of tools provided bootstrapping for but has since been replaced with a Pyramid-specific toolchain.

피라미드의 부트스트랩 도구는 pcreate로 불리며, 피라미드 패키지의 일부이다. 예전에 부트스트랩 도구로 사용했던 the Paste suite of tools 는 피라미드에 특화된 도구로 대체되었다. 


$ pcreate -s starter hello_pyramid # Just make a Pyramid project

Pyramid is intended for bigger and more complex applications than Flask. Because of this, its bootstrapping tool creates a bigger skeleton project. It also throws in basic configuration files, an example template, and the files to package your application for uploading to the Python Package Index.

피라미드는 플라스크보다 더 복잡하고, 커지는 경향이 있다. 이 때문에, 부트스트랩 도구는 더 큰 프로젝트 뼈대를 만든다. 또한 기본적인 파일 설정과, 예시 템플릿, 그리고 파이썬 패키지 인덱스(PyPI)에 올리기 위한 어플리케션을 제공한다. 


hello_pyramid

├── CHANGES.txt

├── development.ini

├── MANIFEST.in

├── production.ini

├── hello_pyramid

│   ├── __init__.py

│   ├── static

│   │   ├── pyramid-16x16.png

│   │   ├── pyramid.png

│   │   ├── theme.css

│   │   └── theme.min.css

│   ├── templates

│   │   └── mytemplate.pt

│   ├── tests.py

│   └── views.py

├── README.txt

└── setup.py

As in the rest of the framework, Pyramid's bootstrapper is incredibly flexible. It's not limited to one default application; pcreate can use any number of project templates. Included in pcreate there is the "starter" template we used above, along with SQLAlchemy- and ZODB-backed scaffold projects. On PyPi it's possible to find ready-made scaffolds for Google App EnginejQuery MobileJinja2 templatingmodern frontend frameworks, and many more.

나머지부분을 보면, 피라미드의 부트스트랩 도구는 엄청나게 유연하다. 하나의 기본 어플리케이션에 제한되지 않는다. pcreate는 프로젝트의 템플릿이 몇개이던지 사용할 수 있다. pcreate에 들어있는 starter 템플릿을 우리는 위에서 사용했는데, SQLAlchemy와 ZODB와 함께 구성했다. PyPi 에서  Google App EnginejQuery MobileJinja2 templatingmodern frontend frameworks, 과 기타 등등의  이미 만들어져 있는 scaffolds를 찾는게 가능하다. 


4.3 Django

Django also has its own bootstrapping tool built in as a part of django-admin.

장고는 또한 django-admin의 일부로서 부트스트랩 툴을 가지고 있다. 

django-admin startproject hello_django

django-admin startapp howdy # make an application within our project

We can already see one of the ways Django differs from Pyramid. Django separates a project into individual applications, where Pyramid and Flask expect a project to be a single "application" with several views or models. It's possible to replicate the project/app distinction in Flask and Pyramid, but the notion does not exist by default.


우리는 이미 장고가 피라미드와 다른 한가지 점을 볼 수 있다. 장고는 피라미드나 플라스크에서 단 한개의 어플리케이션을 한개의 프로젝트와 몇개의 모델이나 뷰를 통해 구성하는 경우에도, 각각의 어플리케이션에 맞추어 프로젝트를 나누어야 한다. 그것은 플라스크나 피라미드는 프로젝트나 앱의 특성을 복제하는 것이 가능하지만, 기본적으로는 그런 개념이 존재하지 않는다. 

hello_django

├── hello_django

│   ├── __init__.py

│   ├── settings.py

│   ├── urls.py

│   └── wsgi.py

├── howdy

│   ├── admin.py

│   ├── __init__.py

│   ├── migrations

│   │   └── __init__.py

│   ├── models.py

│   ├── tests.py

│   └── views.py

└── manage.py

By default Django only includes empty model and template files, so a new user sees a bit less example code to start out. It also (unfortunately) leaves the choice of how to distribute their application to the developer.

장고의 기본은 모델이나 템플릿 파일이 빈것만 포함되어 있고, 새로운 유저는 시작할때 더 적은 예제코드를 볼 수 있다. 그것은 또한 (불행하게도) 개발자에게 어떤식으로 그들의 어플리케이션을 분포시킬지 선택을 남겨뒀다는 뜻이다. 


The downside of the bootstrap tool not guiding users to package their apps is that novice users won't. If a developer hasn't packaged an app before, they'll find themselves rudely surprised upon their first deploy. Projects with a large community like django-oscar are packaged and available on PyPi, but smaller projects on Github often to lack uniform packaging.

부트스트랩 도구의 단점으로는 초짜들에게 출시를 가이드 해주지 않는다는 점이다. 만약에 개발자가 한번도 어플을 출시 해보지 않았다면, 그들은 첫 배포를 위해 상당하 고생을 해야할 것이다. 대형 커뮤니티의 django-oscar같은 프로젝트는 PyPi로 출시가 가능하지만, 깃헙의 더 작은 프로젝트들은 출시에 부족하다. 


5 Templating

Just having a Python application that can respond to HTTP requests is a great start, but it's a good bet that most of your users won't be interested in using curl to interact with your web app. Fortunately, all three contenders provide an easy way to fill in HTML with custom info, and let folks enjoy your swanky Bootstrap frontend.

단순히 HTTP 요청에 응답하는 파이썬 어플리케이션을 갖는다는것은 좋은 출발이다. 하지만, 당신의 대부분의 사용자들은 curl을 이용해서 당신의 웹앱과 상호작용하지 않을것이다. 다행히도, 이 세가지의 경쟁자들은 HTML을 커스텀화해서 채우고, 부트스트랩을 이용한 프론트엔드를 다루는데 쉬운 방법을 제공한다.  


Templating lets you inject dynamic information directly into your page without using making AJAX requests. This is nice from a user experience perspective since you only need to make one round-trip to get the full page and all its dynamic data. This is especially important on mobile sites where round trips can take multiple seconds.

이 템플릿은 당신의 페이지를 AJAX 요청으로 만들지 않더라도, 동적 정보를 삽입 할 수 있다. 이것은 한번의 전체 페이지와 동적 데이타를 전부 받아서 보여준다는 것으로, 사용자경험적 측면에서도 좋다. 이것은 특히 모바일 사이트에서 한번 정보를 주고받는데 몇초씩 걸리는 상황에서 아주 중요하다. 


All the templating options we'll see rely on a "context" that provides the dynamic information for the template to render into HTML. The simplest use case for a template would be to populate a logged-in user's name to greet them properly. It would be possible to use AJAX to get this sort of dynamic information, but requiring a whole call just to fill in a user's name would be a bit excessive when templates are this easy.

모든 템플릿화 옵션은 우리는 HTML로 그리는 템플릿을 위한 동적인 정보를 제공하는 “컨텍스트”에 의존하는 것을 할 수있다. 가장 단순하게 템플릿을 사용하는 경우는  유저로그인-환영메세지를 템플릿 하는경우다. AJAX를 이용해 이런 동적정보를 얻어내는것이 가능하지만, 겨우 유저이름을 채우는데에 전체 요청을 요구하는것은 조금 낭비일 수 있다. 


5.1 Django

Our example use case is about as easy as it gets, assuming that we have a userobject that has a fullname property containing a user's name. In Python we'd pass the current user to the template like so:

우리의 예제는 어떤 이름을 가진 유저객체에서, fullname 속성을 가져오는것이 얼마나 쉬운지 나타내준다. 파이썬에서 우리는 현재 유저의 탬플릿을 이렇게 통과시킨다. 


def a_view(request):

    # get the logged in user

    # ... do more things

    return render_to_response(

        "view.html",

        {"user": cur_user}

    )

Populating the template context is as simple as passing a dictionary of the Python objects and data structures the template should use. Now we need to render their name to the page, just in case they forget who they are.

템플릿 컨텍스트를 채우는것은 파이썬객체의 딕셔너리와 템플릿이 사용하는 대에터 구조만큼이나 단순하다. 이제 우리는 그들의 이름을 페이지에 그릴 필요가 있으니, 일단 그들이 누군지 잠깐 까먹자. 


<!-- view.html -->

<div class="top-bar row">

  <div class="col-md-10">

  <!-- more top bar things go here -->

  </div>

  {% if user %}

  <div class="col-md-2 whoami">

    You are logged in as {{ user.fullname }}

  </div>

  {% endif %}

</div>


First, you'll notice the {% if user %} construct. In Django templates {% is used for control statements like loops and conditionals. The if user statement is there to guard against cases where there is not a user. Anonymous users shouldn't see "you are logged in as" in the site header.

첫번째로, {% if user %}구조가 보일 것이다. 장고템플릿에서 {% 는 순환문과 조건문 처럼 쓰인다. if user 문장은 유저가 아닌경우를 막아준다. 익명의 유저는 당신은 **로 로그인 했습니다. 를 머릿글에서 볼 수 없다. 


Inside the if block, you can see that including the name is as simple as wrapping the property we want to insert in {{ }}. The {{ is used to insert actual values into the template, such as {{ user.fullname }}.

블록 안에서, 이름은 단순히 우리가 삽입사고 싶은 속성을 {{ }} 안에 넣는것을 볼수 있다. {{는 {{user.fullname}} 처럼 템플릿 안에 실제 값을 넣어서 사용하게된다. 


Another common use for templates is displaying groups of things, like the inventory page for an ecommerce site.

다른 흔한 템플릿 사용법은 판매용 장바구니 페이지처럼 몇몇 요소를 그룹화해서 표현하는 것이다. 

def browse_shop(request):

    # get items

    return render_to_response(

        "browse.html",

        {"inventory": all_items}

    )


In the template we can use the same {% to loop over all the items in the inventory, and to fill in the URL to their individual page.

템플릿 안에서 우리는 장바구니 안에있는 물건들을 같은 {% 을 이용해서 반복해서 나타 낼 수 있다. 그리고 개개인의 페이지에 맞게 URL을 만들 수 있다. 

{% for widget in inventory %}

    <li><a href="/widget/{{ widget.slug }}/">{{ widget.displayname }}</a></li>

{% endfor %}

To do most common templating tasks, Django can accomplish the goal with just a few constructs, making it easy to get started.

가장 흔한 템플릿작업을 하기 위하여, 장고는 아주 적은 구조를 가지고 목표를 완성할 수 있고, 쉽게 만들고, 시작할 수 있다. 


5.2 Flask

Flask uses the Django-inspired Jinja2 templating language by default but can be configured to use another language. A programmer in a hurry couldn't be blamed for mixing up Django and Jinja templates. In fact, both the Django examples above work in Jinja2. Instead of going over the same examples, let's look at the places that Jinja2 is more expressive than Django templating.

플라스크는 장고의 영향을 받은 Jinja2 템플릿 언어를 기본으로 사용하고 있지만, 다른 언어로 바꿔서 설정 할 수 있다. 바쁜 프로그래머는 장고와 진자 템플릿을 섞어놓는 것에 욕먹을 수 없다. 사실 위의 두 장고 예제는 진자2에서도 돌아간다. 똑같은 예제를 보여주는 대신에, 우리는 장고 템플릿보다 좀더 특급의 진자2 예제를 보자. 


Both Jinja and Django templates provide a feature called filtering, where a list can be passed through a function before being displayed. A blog that features post categories might make use of filters to display a post's categories in a comma-separated list.

진자와 장고 템플릿 둘다 필터링이라 불리는 기능을 제공하는데, 이것은 화면에 표현되기 전에 리스트가 함수를 지나칠 수 있다는 것이다. 블로그의 카테고리 기능은 하나의 포스트가 가지는 콤마로 구분되는 카테고리를 필터링 하게 해야한다. 


<!-- Django -->

<div class="categories">Categories: {{ post.categories|join:", " }}</div>


<!-- now in Jinja -->

<div class="categories">Categories: {{ post.categories|join(", ") }}</div>


In Jinja's templating language it's possible to pass any number of arguments to a filter because Jinja treats it like a call to a Python function, with parenthesis surrounding the arguments. Django uses a colon as a separator between the filter name and the filter argument, which limits the number of arguments to just one.

진자의 템플릿 언어는 필터리의 주제가 몇개던지 간에 패스 할 수 있다. 외댜하면 진자는 중괄호로 둘러싸인 부분을 파이썬 함수를 호출하듯이 다루기 때문이다. 장고는 필터이름과 필터 주제를 구분하는 구분자로 콜론을 사용한다. 이는 갯수 제한이 있다. 


Jinja and Django for loops are also similar. Let's see where they differ. In Jinja2, the for-else-endfor construct lets you iterate over a list, but also handle the case where there are no items.

진자와 장고는 for문에서 또한 비슷하다. 어디서 그들이 다른지 알아보자. 진자에서는 for-else-endfor 구조가 리스트 뿐만아니라 객체가 없는 경우에도 사용할 수 있다. 


{% for item in inventory %}

<div class="display-item">{{ item.render() }}</div>

{% else %}

<div class="display-warn">

<h3>No items found</h3>

<p>Try another search, maybe?</p>

</div>

{% endfor %}


이 부분에서 장고의 버전은 기능적으로 동일하지만 for-else-endfor를 사용하는 대신에, for-empty-endfor를 사용한다. 


{% for item in inventory %}

<div class="display-item">{{ item.render }}</div>

{% empty %}

<div class="display-warn">

<h3>No items found</h3>

<p>Try another search, maybe?</p>

</div>

{% endfor %}


Other than the syntactic differences above, Jinja2 provides more control over its execution environment and advanced features. For example, it's possible to disable potentially dangerous features to safely execute untrusted templates, or to compile templates ahead of time to ensure their validity.

몇가지 다른 문법적 차이가 있고, 진자2는 실행환경이에대한 조절과 심화기능을 제공한다. 예를들면, 신뢰할수 없는 템플릿을 안전하게 실행하기 위해 미리 위험한 기능을 끄는 것이 가능하고, 또는 그것들의 효력을 측정해서 컴파일 할 수 있다. 


5.3 Pyramid

Like Flask, Pyramid supports many templating languages (including Jinja2 and Mako) but ships with one by default. Pyramid uses Chameleon, an implementation of ZPT(the Zope Page Template) templating language. Let's look back at our first example, adding a user's name to the top bar of our site. The Python code looks much the same except that we don't need to explicitly call a render_template function.

플라스크 처럼, 피라미드는 많은 템플릿 언어를 지원한다(진자, 마코를 포함해서) 하나가 기본 설정이다. 피라미드는 카멜레온을 사용한다. 카멜레온은 ZPT 을 이식한 템플릿 언어이다. 자, 다사ㅣ 우리의 첫번째 예제로 돌아가 보자. 유저의 이름을 우리의 사이트 맨 위에 추가하려고 한다. 파이썬 코드는  render_template 함수를 명시적으로 호출 하지 않는다는것을 제외하면 동일해 보인다. 


@view_config(renderer='templates/home.pt')

def my_view(request):

    # do stuff...

    return {'user': user}


But our template looks pretty different. ZPT is an XML-based templating standard, so we use XSLT-like statements to manipulate data.

하지만 우리의 템플릿은 완전 달라보인다. ZPT는 XML기반의 템플릿 기준으로써, 우리는 XSLT처럼 보이는 문장을 데이터를 가공하는 데 사용한다. 


<div class="top-bar row">

  <div class="col-md-10">

  <!-- more top bar things go here -->

  </div>

  <div tal:condition="user"

       tal:content="string:You are logged in as ${user.fullname}"

       class="col-md-2 whoami">

  </div>

</div>


Chameleon actually has three different namespaces for template actions. TAL (template attribute language) provides basics like conditionals, basic string formatting, and filling in tag contents. The above example only made use of TAL to complete its work. For more advanced tasks, TALES and METAL are required. TALES (Template Attribute Language Expression Syntax) provides expressions like advanced string formatting, evaluation of Python expressions, and importing expressions and templates.

카멜레온은 사실 템플릿 작용을 하기 위해 세개의 다른 이름공간을 가지고 있다. 


METAL (Macro Expansion Template Attribute Language) is the most powerful (and complex) part of Chameleon templating. Macros are extensible, and can be defined as having slots that are filled when the macro is invoked.

METAL은 카멜레온 템플릿의 가장 강력한 부분이다. 매크로가 확장가능하고, 매크로가 호출되었을때, 어떤 슬롯이 그것을 채울 수 있는지 정의 될 수 있다.





헥헥... 6장이랑 나머지는 다음에... 이거이거  보통일이 아니다. ㅠ


뒤에 부분은 프레임워크가 어떻게 작동하는지. 그리고 요약이다. 

사실 나는 결론 냈다. ㅠㅠ 플라스크로 할꺼다.