Welcome to the third part of our Flask Tutorials series! Today, we're going to dive deep into the Werkzeug utilities that come bundled with Flask. If you're new to Flask, don't worryβwe'll start from the ground up. Let's get started!
Werkzeug is a Swiss Army knife for Python web development. It provides a collection of utilities that make web development easier, more convenient, and more efficient. Flask includes Werkzeug by default.
Although Flask includes Werkzeug, you can install it separately if needed. Here's how:
pip install WerkzeugWerkzeug provides a powerful URL routing system that enables you to map URLs to functions. This is fundamental to building web applications.
from werkzeug.routing import Map, Rule
routes = Map({
Rule('/', 'index'),
Rule('/about', 'about')
})
def index():
return 'Welcome to CodeYourCraft!'
def about():
return 'About CodeYourCraft'
# Routing the URLs
@app.route('/')
def index():
return routes.dispatch_on_url('/')
@app.route('/about')
def about():
return routes.dispatch_on_url('/about')The request object contains all information about the current request, such as the requested URL, HTTP method, headers, cookies, and form data.
from werkzeug.request import Request
def test_request():
fake_request = Request(method='GET', url='http://example.com', headers={'Host': 'example.com'})
print(fake_request.method) # Output: GET
print(fake_request.url) # Output: http://example.com
print(fake_request.headers['Host']) # Output: example.comWhat is Werkzeug?
The Response object allows you to create custom HTTP responses.
from werkzeug.responses import Response
def custom_response():
response = Response('Hello, World!', mimetype='text/plain')
return responseWerkzeug provides a way to set and read secure cookies, which are cookies that are sent only over HTTPS.
from werkzeug.security import generate_password_hash, check_password_hash
def set_secure_cookie():
response = Response()
response.set_cookie('user_id', '12345', secure=True)
def check_secure_cookie():
user_id = request.cookies.get('user_id')
# Verify the user_idWerkzeug can handle file uploads and downloads easily.
from werkzeug.utils import secure_filename
def upload_file():
if 'file' not in request.files:
return 'No file part'
file = request.files['file']
if file.filename == '':
return 'No selected file'
filename = secure_filename(file.filename)
file.save(filename)
return f'File {filename} uploaded successfully'
def download_file():
return send_from_directory(directory, filename)How can you create a custom HTTP response in Flask using Werkzeug?
And there you have it! This is a brief introduction to the Werkzeug utilities available in Flask. We've covered the basics and intermediate concepts, but Werkzeug has much more to offer. Keep exploring and learning!
Stay tuned for our next Flask Tutorials lesson, where we'll dive into Flask templates. π