First, create a new directory for your project and open a terminal in that directory. Then, run the following command to create a new virtual environment for your project:
# For windows:
virtualenv venv
# For linux:
python3 -m venv venv
Activate the virtual environment by running the following command:
# For windows
venv/Scripts/activate
# For linux
source venv/bin/ activate
Next, install Flask by running the following command:
pip install Flask
Create a file named Create a new file for app.py
and add the following code to set up a basic Flask application:
from flask import Flask, request, redirect app = Flask(__name__) @app.route('/') def index(): return 'Welcome to the URL Shortener' if __name__ == '__main__': app.run(debug=True)
Run the following command to start the Flask development server:
python app.py
In your Visit http://localhost:5000
in your web browser to view the "Welcome to URL Shortener" message.
Next, we will store the original URL and its corresponding shortened URL in a Python dictionary. Add the following code to your app.py
file:
url_map = {} @app.route('/shorten', methods=['POST']) def shorten_url(): original_url = request.form['url'] short_url = generate_short_url(original_url) url_map[short_url] = original_url return short_url def generate_short_url(original_url): # Generate a unique short URL for the original URL # (We'll implement this in the next step) pass
To generate unique short URLs, we will use ha Greek function. A hash function takes an input (in this case, a raw URL) and returns a fixed-length output (a short URL). We will use the SHA-1 hash function, which is part of the Pythonhashlib library. Add the following code to your app.py file: The user is redirected to the original URL. Add the following code to your
app.pyimport hashlib def generate_short_url(original_url): hash = hashlib.sha1(original_url.encode()) short_url = hash.hexdigest()[:8] return short_url
The above is the detailed content of Use Python Flask to build an efficient and concise URL shortening service. For more information, please follow other related articles on the PHP Chinese website!