1. Install Flask: Before you can use the Flask framework, you must install it. You can do this by running pip install flask from the command line.
2. Create a Flask App: Create a file named app.py and add the following code to it:
from flask import Flask
app = Flask(__name__)
@app.route(„/”)
def hello():
return „Hello, World!”
if __name__ == „__main__”:
app.run()
This code creates a basic Flask application with a single route that returns the string “Hello, World!” when you visit the root URL.
3. Run the App: To run the app, you can use the flask command. Navigate to the directory containing app.py and run the following command:
$ flask run
This will start the Flask development server and you can now visit http://localhost:5000/ to see the “Hello, World!” message.
4. Add Views and Templates: Now that you have a basic Flask app running, you can start adding views and templates. Views are the functions that are mapped to specific URLs and they are responsible for returning the response. Templates are HTML files that are used to render the response.
For example, you can add a view that returns a rendered template:
@app.route(„/hello”)
def hello_template():
return render_template(„hello.html”)
This view will render the hello.html template when you visit http://localhost:5000/hello.
5. Add Static Files: You can also add static files such as CSS, JavaScript, and images to your Flask app. These files should be placed in a static directory inside your project directory. You can then link to them from your templates.
For example, you can add a stylesheet to your project and link to it from your templates:
Now you can use the Flask framework to create web applications with Python.
Legutóbbi hozzászólások