Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Packaging and Deployment — Deploying to Railway

Packaging and Deployment — Deploying to Railway

In this chapter you will learn the application factory pattern, production environment configuration, and how to deploy a Flask blog to Railway.


Application Factory Pattern create_app()

So far, app.py directly creates app = Flask(__name__), which is sufficient during development, but has a few problems:

The application factory pattern solves these problems: encapsulate app creation in a function.

Example

File path: app/init.py

from

flask

import

Flask

from

flask_sqlalchemy

import

SQLAlchemy

from

flask_login

import

LoginManager

from

flask_migrate

import

Migrate

from

config

import

Config

db

=

SQLAlchemy

(

)

login_manager

=

LoginManager

(

)

migrate

=

Migrate

(

)

def

create_app

(

config_class

=

Config

)

:

   

"""Application factory: create a Flask application instance based on a config class"""

    app

=

Flask

(

name

)

    app.

config

.

from_object

(

config_class

)

   

Initialize extensions (first create the app instance, then bind extensions to the app)

    db.

init_app

(

app

)

    login_manager.

init_app

(

app

)

    migrate.

init_app

(

app

,

db

)

    login_manager.

login_view

=

'auth.login'

    login_manager.

login_message

=

'Please log in before accessing.'

   

Register Blueprint

   

from

app.

blueprints

.

main

import

main_bp

   

from

app.

blueprints

.

posts

import

posts_bp

   

from

app.

blueprints

.

auth

import

auth_bp

   

from

app.

blueprints

.

user

import

user_bp

    app.

register_blueprint

(

main_bp

)

    app.

register_blueprint

(

posts_bp

)

    app.

register_blueprint

(

auth_bp

)

    app.

register_blueprint

(

user_bp

)

   

user_loader must be defined after the app exists

   

from

app.

models

import

User

   

@

login_manager.

user_loader

   

def

load_user

(

user_id

)

:

       

return

User.

query

.

get

(

int

(

user_id

)

)

   

return

app

Configuration file config.py

Example

File path: config.py

import

os

from

dotenv

import

load_dotenv

Load environment variables from a .env file (development only)

load_dotenv

(

)

class

Config:

    SECRET_KEY

=

os

.

environ

.

get

(

'SECRET_KEY'

,

'dev-secret-key'

)

    SQLALCHEMY_DATABASE_URI

=

os

.

environ

.

get

(

'DATABASE_URL'

,

'sqlite:///blog.db'

)

    SQLALCHEMY_TRACK_MODIFICATIONS

=

False

class

DevelopmentConfig

(

Config

)

:

    DEBUG

=

True

class

ProductionConfig

(

Config

)

:

    DEBUG

=

False

Select configuration based on environment variables

config_map

=

{

   

'development'

: DevelopmentConfig

,

   

'production'

: ProductionConfig

,

   

'default'

: DevelopmentConfig

}

New entry file wsgi.py

Example

File path: wsgi.py

from

app

import

create_app

app

=

create_app

(

)

The startup method now becomes:



(venv) $ flask --app wsgi run --debug      # 开发模式

(venv) $ gunicorn wsgi:app                  # 生产模式(Gunicorn)

Note the import order: Blueprint and user_loader must be imported inside create_app() (not at the top of the file), otherwise a circular import will occur (Blueprint references models, models references db, and db is not yet bound to the app at that point).


Generate requirements.txt and Procfile



(venv) $ pip freeze > requirements.txt

Ensure the file contains key dependencies: Flask, Flask-SQLAlchemy, Flask-Migrate, Flask-Login, Flask-WTF, Flask-Admin, gunicorn, python-dotenv.

Create in the project root directory Procfile:



web: gunicorn wsgi:app


Push the Project to GitHub



$ git init

$ echo "venv/" > .gitignore

$ echo "__pycache__/" >> .gitignore

$ echo "*.pyc" >> .gitignore

$ echo "instance/" >> .gitignore

$ echo ".env" >> .gitignore

$ git add .

$ git commit -m "初始化 Flask 博客项目"

$ git branch -M main

$ git remote add origin https://github.com/你的用户名/flask-blog.git

$ git push -u origin main

Be sure to add .env Add to .gitignore. The .env file contains sensitive information such as SECRET_KEY; once committed to GitHub it cannot be completely removed (Git history will retain it).


Railway Deployment

  1. Access the railway.app, log in with GitHub
  2. New Project → Deploy from GitHub repo → select flask-blog
  3. Railway automatically detects the Procfile and recognizes the Gunicorn startup command
  4. Set environment variables in Variables
  5. Click Deploy

Environment variable configuration

Variable Name Value Description
SECRET_KEY A randomly generated long string Encrypt Session and CSRF Token
DATABASE_URL Automatically injected by Railway Production database (PostgreSQL provided by Railway)
FLASK_ENV production Production environment identifier

Quickly generate a SECRET_KEY:



$ python -c "import secrets; print(secrets.token_urlsafe(50))"

After successful deployment, you get a link like https://flask-blog.up.railway.app。


Next Learning Directions

Learning Direction Who It's For Recommended Starting Point
Flask REST API Building an API for frontend frameworks (Vue3/React) Use jsonify instead of render_template to build a RESTful API
Flask + Vue3/React frontend-backend separation Want to use Flask as the backend and Vue3/React as the frontend Flask provides a JSON API, and the frontend communicates via fetch
PostgreSQL Need a production-grade database Replace SQLite, install psycopg2, and modify DATABASE_URL
Docker deployment Containerized deployment Write a Dockerfile and orchestrate with docker-compose