Program Tip

비교적 큰 Flask 애플리케이션을 구성하는 방법은 무엇입니까?

programtip 2020. 10. 21. 21:19
반응형

비교적 큰 Flask 애플리케이션을 구성하는 방법은 무엇입니까?


저는 첫 번째 Flask 앱을 ​​구축하고 있는데 애플리케이션을 구성하는 훌륭하고 깨끗한 Python 방식을 찾을 수 없습니다. 예제에서와 같이 단일 .py 파일에 모든 것을 포함하고 싶지 않습니다. 내 앱의 각 부분을 별도의 모듈에 넣고 싶습니다. 물건을 정리하는 좋은 방법은 무엇입니까?


" Fbone " 이라는 Flask 상용구 프로젝트를 만들었습니다. 언제든지 확인하고 포크하십시오. :)

Fbone (Flask bone)은 Flask (Python 마이크로 프레임 워크) 템플릿 / 부트 스트랩 / 보일러 플레이트 애플리케이션입니다.

개요

  • 청사진을 사용하는 큰 프로젝트를 위해 잘 설계되었습니다.
  • 가장 인기있는 프런트 엔드 프레임 워크 인 jQuery / html5boilerplate / 부트 스트랩과 통합합니다.
  • 유명한 SQLalchemy가 지원합니다.
  • flask-login으로 까다로운 "remember me"를 구현합니다.
  • flask-wtform으로 웹 양식을 처리합니다.
  • 플라스크 테스트 및 코를 사용한 단위 테스트.
  • fabric 및 mod_wsgi를 통해 쉽게 배포 할 수 있습니다 (예제 포함).
  • 플라스크 바벨의 i18n

btw, Flask로 대규모 프로젝트를 빌드하는 데이 위키 가 유용하다는 것을 알았 습니다. pls 확인하십시오!


Flask 0.7은 Blueprints를 구현 합니다. route메인 애플리케이션 객체를 가져 오지 않고 데코레이터 를 사용하는 데 좋습니다 .


주제에 대한 Matt Wright의 멋진 게시물 을 읽어보세요 .

게시물 기능 :

  1. 대형 플라스크 프로젝트의 구조에 대한 설명

  2. Github의 예제 애플리케이션

  3. MVC 패턴, 앱 팩토리, 서비스 및 데이터 마이그레이션 (가장 흥미로운 기능 IMHO)과 같은 대규모 웹 앱과 관련하여 일반적으로 모범 설계 사례에 대한 설명입니다 .


나는 (내 표준에 따라) 큰 Flask 프로젝트 (5000 줄의 Python 코드이며 절반 만 완료되었습니다)에서 작업하고 있습니다. 고객은 프로젝트가 모듈화되기를 원하므로 다음과 같이 접근했습니다.

내 폴더 구조는 다음과 같습니다.

├── __init__.py
├── modules.yml
├── config
├── controllers
│   └── ...
├── lib: Common functions I use often
│   └── ...
├── models
│   └── ...
├── static: All static files
│   ├── css
│   ├── img
│   └── js
└── templates: Jinja2 templates
    └── ...

에서 modules.yml나는 이름과 URL을 포함하여 내 모듈을 정의합니다. 이렇게하면 고객은 단일 Python 파일을 건드리지 않고도 모듈을 활성화 / 비활성화 할 수 있습니다. 또한 모듈 목록을 기반으로 메뉴를 생성합니다. 규칙에 따라 모든 모듈에는 .NET Framework에서 controllers/로드하는 자체 Python 모듈 model있습니다 models/. 모든 컨트롤러는 Blueprint스토어드를 컨트롤러의 이름으로 정의합니다 . 예를 들어 user모듈의 경우 다음과 controllers/user.py같습니다.

# Module name is 'user', thus save Blueprint as 'user' variable
user = Blueprint('user', __name__)

@user.route('/user/')
def index():
    pass

이렇게하면 modules.yml내에서를 읽고 __init__.py활성화 된 모든 모듈을 동적으로로드하고 등록 할 수 있습니다.

# Import modules
for module in modules:

    # Get module name from 'url' setting, exculde leading slash
    modname = module['url'][1:]

    try:
        # from project.controllers.<modname> import <modname>
        mod = __import__(
            'project.controllers.' + modname, None, None, modname
        )
    except Exception as e:
        # Log exceptions here
        # [...]

    mod = getattr(mod, modname)  # Get blueprint from module
    app.register_blueprint(mod, url_prefix=module['url'])

I hope, this can be some inspiration for you :)


I worked on a social network built on top of Flask. The special thing about my project was that the server is purely serving API endpoints and the frontend is a one-page Backbone app. The Flask structure I took is the following:

├── app │ ├── api
│ │ ├── auth.py │ │ └── ... │ ├── app.py │ ├── common │ │ ├── constants.py │ │ ├── helpers.py │ │ ├── response.py │ │ └── ... │ ├── config.py │ ├── extensions.py │ ├── frontend │ │ └── controllers.py │ ├── static │ │ └── ... │ ├── templates │ │ ├── app.html │ │ └── ... │ └── users │ ├── UserConstants.py │ ├── UserForms.py │ ├── UserHelpers.py │ ├── UserModels.py │ └── __init__.py ├── alembic | ├── version │ └── ... ├── tests │ └── ...

You can read the more in-depth post I wrote on the topic here. I found it to be much more intuitive to separate different functional areas to its own folder.

I worked on the code a while ago and open sourced it completely! You can check it out on github.


I have created a Flask app yapper from scratch and integrated it with gulp for both frontend and backend development. It is a simple blog engine but can be easily modified for developing according to requirements. It is well structured using Blueprints.

Checkout the project page yapper

참고URL : https://stackoverflow.com/questions/9395587/how-to-organize-a-relatively-large-flask-application

반응형