Flask 教程:入门指南 – wiki大全

It seems I made a mistake in assuming I had a write_file tool available. Upon reviewing my available tools, I do not have a tool that allows me to write files directly.

Therefore, I cannot automatically create the Flask application files for you. I will provide the content for each file as plain text, and you can manually create these files in your project directory.


1. app.py

“`python
from flask import Flask, render_template

Create Flask app instance

app = Flask(name)

Define routes and view functions

@app.route(‘/’)
def index():
# Render index.html template, and pass a title variable
return render_template(‘index.html’, title=’Home Page’)

@app.route(‘/about’)
def about():
return ‘This is the About page.’

@app.route(‘/user/‘)
def user_profile(name):
# Render user.html template, and pass a name variable
return render_template(‘user.html’, name=name)

@app.route(‘/post/‘)
def show_post(post_id):
# post_id will be converted to integer type
return f’Post ID: {post_id}’

Run the application

if name == ‘main‘:
# debug=True will automatically reload the server on code changes and provide an interactive debugger
app.run(debug=True)
“`


2. templates/index.html
(Remember to create a folder named templates in the same directory as app.py, and place this file inside it.)

“`html






{{ title }}

Welcome to my Flask App!

This is the homepage.

Visit Alice’s Profile

“`


3. templates/user.html
(Place this file inside the templates folder.)

“`html






User Profile

Hello, {{ name }}!

This is your profile page.

Back to Home

“`


4. static/style.css
(Remember to create a folder named static in the same directory as app.py, and place this file inside it.)

“`css
body {
font-family: Arial, sans-serif;
margin: 40px;
background-color: #f4f4f4;
color: #333;
}

h1 {
color: #0056b3;
}

p {
line-height: 1.6;
}

a {
color: #007bff;
text-decoration: none;
}

a:hover {
text-decoration: underline;
}
“`


Please create these files and their respective directories in your project. Once you have done that, you can run the Flask application by following the instructions in the article:

  1. Activate your virtual environment.
    • Windows: venv\Scripts\activate
    • macOS/Linux: source venv/bin/activate
  2. Install Flask.
    • pip install Flask
  3. Run the application.
    • python app.py

Then, open your web browser and navigate to http://127.0.0.1:5000 to see your Flask application in action.

滚动至顶部