"Flask" organizes flask large project file structures on Pycharm

Source: Internet
Author: User
Tags auth sqlite virtual environment
Overview

To develop a large project with flask, you must have a good project file structure, which records the configuration of the Flask minimum development project. The Python version used here is 3.5.1,flask version 0.11.1. test Environment Python version: 3.5.1 flask version: 0.11.1 pycharm version: 5.0.3 main directory

The main catalogue is as follows:
folder Description app

App for the folder where the application is placed, the main auth and Models,auth are placed flask the Blueprint program, models put the operation of the database code. Auth's __init__.py

The main configuration blueprint:

From flask import Blueprint

auth = Blueprint (' auth ', __name__)
the __init__.py of the app

The __init__.py code for the app is as follows:

# Coding=utf-8 from
flask import flask to
flask_sqlalchemy import sqlalchemy from

Config import config

db = SQLAlchemy ()


def Create_app (config_name):
    app = Flask (__name__)
    app.config.from_object (config [Config_name])
    Config[config_name].init_app (APP)

    Db.init_app (APP)
    Db.app = App

    # Registration Blueprint
    # Add auth Blueprint
    from App.auth Import auth as Auth_blueprint
    app.register_blueprint (auth_blueprint, url_prefix= '/auth ')

    # Additional Routing and custom error pages return

    app
tests

The tests folder is the Test folder, and the code to write unit tests is here. Here is a sample code for a unit test:

# test_basic.py
import unittest
from flask import Current_app
from app import Create_app, DB

class Basictestcase (unittest. TestCase): The
    SetUP () and teardown () methods run before and after each test,
    and functions that begin with the name Test_ are executed as tests. "" "
    def setUp (self):" "" ""
        Self.app = Create_app (' testing ') before each unit test runs
        Self.app_context = Self.app.app_context ()
        Self.app_context.push ()
        Db.create_all ()

    def teardown (self): ""
        The "" "
        Db.session.remove ()
        db.drop_all ()
        Self.app_context.pop ()

    def Test_app_ is invoked after each unit test execution ends. Exists (self): "" "
        test to ensure that an instance of the program exists" "
        Self.assertfalse (Current_app is None)

    def test_app_is_testing (self) : "" The
        test ensures that the program runs in the test Configuration ""
        self.asserttrue (current_app.config[' testing ')

venv

Venv is the private package where the virtual environment is placed.

A virtual environment is a private copy of the Python interpreter, where you can install a private package and will not affect the global Python interpreter installed in the system.

To set up a virtual environment in Pycharm:

Click the Setting button on the right, will pop up the following window, click "create virtualenv" and then set "local" and "name" for the current project directory venv can.


Once you have set up your virtual environment, you can start downloading the Flask development package you need. config.py

config.py for the configuration of the project, which includes the development environment, test environment and configuration of the production environment, as follows:

Import OS basedir = Os.path.abspath (Os.path.dirname (__file__)) class Config:secret_key = Os.environ.get (' Secret_key ' ) or ' hard to guess string ' Sqlalchemy_commit_on_teardown = True flasky_mail_subject_prefix = ' [Flasky] ' flask Y_mail_sender = ' Flasky Admin <flasky> @example. com ' flasky_admin = os.environ.get (' flasky_admin ') @staticme Thod def init_app (APP): Pass class Developmentconfig (Config): DEBUG = True Sqlalchemy_database_uri = Os.environ.get (' dev_database_url ') or \ ' sqlite:///' + os.path.join (basedir, ' data-dev.sqlite ') Sqlalchemy_tra Ck_modifications = True class Testingconfig (Config): testing = True wtf_csrf_enabled = False Sqlalchemy_datab Ase_uri = Os.environ.get (' test_database_url ') or \ ' sqlite:///' + os.path.join (basedir, ' data-test.sqlite ') SQ Lalchemy_track_modifications = True class Productionconfig (Config): Sqlalchemy_database_uri = Os.environ.get (' Databas E_url ') or \ ' sqlite:///' + os.path.join (basedir, ' data.sqlite ') sqlalchemy_track_modifications = True config = {' Development ': Developmentconfig, ' testing ': testingconfig, ' prodection ': productionconfig, ' Default ': Developmentconfig}
manage.py

Manage.py is a startup script that is used by flask to start a program that reads as follows:

Import OS
from flask_migrate import migrate, Migratecommand to
flask_script import Manager, Shell from
app Import Create_app, db

app = Create_app (os.getenv (' flask_config ') or ' default ')
Manager = Manager (APP)
Migrate = Migrate (app, db)

def make_shell_context (): Return
    dict (App=app, db=db)

Manager.add_command (" Shell ", Shell (make_context=make_shell_context))
Manager.add_command (" db ", Migratecommand)

@ Manager.command
def Test (): "" "Run the unit
    tests.
    " " Import unittest
    tests = unittest. Testloader (). Discover (' tests ')
    unittest. Texttestrunner (verbosity=2). Run (Tests)

if __name__ = = ' __main__ ':
    manager.run ()
Requirements File

You can have a requirements.txt file in your program that records all dependent packages and their exact version numbers.

Pip Freeze > Requirements.txt

After installing or upgrading the package, be sure to update the file.
When you need to import, install a variety of packages:

Pip Install-r requirements.txt other

The following is an example of an interface design that returns JSON format, as well as adding database interfaces and ORM. Returns JSON data to use jsonify.

auth/users.py contents are as follows:

From flask Import request, jsonify from
app.models import * from
app.auth import auth

@auth. Route ('/apidemo ' , methods=[' get ', ' POST ']
def apidemo (): "" "
    a design example that returns a JSON data interface" "

    jsonresponse = Dict (errcode=" 1 ", Errmsg= "Operation succeeded. ")
    response = jsonify (jsonresponse) return
    response

In addition, at the end of the auth/__init__.py, add from. Users Import *

From flask import Blueprint

auth = Blueprint (' auth ', __name__) from

. Users Import *

models/users.py contents are as follows:

from app Import DB Class User (db. Model): __tablename__ = ' users ' id = db. Column (db. Integer, primary_key=true) Usercode = db. Column (db. String (), Unique=true, index=true) Password = db. Column (db. String (128)) def __init__ (self, Usercode=none, password=none): self. Usercode = Usercode self. Password = Password def __repr__ (self): return ' <user%r> '% self. UserName 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.