Python Web Development: Create HTML Forms with Flask & Run on Windows
To create an HTML form using Python, you can use the Flask web framework. Here's an example:
- Install Flask using pip:
pip install Flask
- Create a new Python file called 'app.py' and add the following code:
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('form.html')
@app.route('/submit', methods=['POST'])
def submit():
name = request.form['name']
email = request.form['email']
message = request.form['message']
return f"Name: {name}, Email: {email}, Message: {message}"
if __name__ == '__main__':
app.run(debug=True)
- Create a new HTML file called 'form.html' and add the following code:
<!DOCTYPE html>
<html>
<head>
<title>HTML Form Example</title>
</head>
<body>
<h1>HTML Form Example</h1>
<form action="/submit" method="POST">
<label>Name:</label>
<input type="text" name="name"><br><br>
<label>Email:</label>
<input type="email" name="email"><br><br>
<label>Message:</label>
<textarea name="message"></textarea><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
-
Run the Python file using the command
python app.pyand go to http://localhost:5000 in your web browser. You should see the HTML form. -
Enter some values in the form and click the "Submit" button. You should see a new page that displays the values you entered.
Web Servers on Windows
The most commonly used web server on Windows is IIS (Internet Information Services). However, there are also other options such as Apache and Nginx.
Why Use Flask?
Flask is a lightweight web framework for Python that allows you to easily create web applications. It is a popular choice for small to medium-sized projects due to its simplicity and flexibility.
Understanding if __name__ == '__main__':
The if __name__ == '__main__': statement is used to ensure that the code inside it is only executed when the script is run directly, and not when it is imported as a module into another script. The app.run(debug=True) function starts the Flask development server with debug mode enabled, which allows you to see any errors or issues that occur during development.
原文地址: https://www.cveoy.top/t/topic/lB8Q 著作权归作者所有。请勿转载和采集!