Wednesday, June 21, 2023

How to Install Flask in Windows Python3 Setup VS Code virtual environment follow these simple basic steps for beginners

To install Flask on Windows in a virtual environment, you can follow these steps:

1. Install Python: Visit the official Python website at https://www.python.org/downloads/ and download the latest version of Python 3.x for Windows. Run the installer and make sure to check the box that says "Add Python to PATH" during the installation process.

2. Open a command prompt: Press `Win + R` on your keyboard, type `cmd`, and hit Enter. This will open a command prompt.

3. Create a virtual environment: In the command prompt, navigate to the directory where you want to create your virtual environment. Use the `cd` command to change directories. For example, if you want to create a virtual environment in a folder named "myproject," you can use the following command:

   cd C:\path\to\myproject

     Once you are in the desired directory, create the virtual environment by running the following command:

   python -m venv myenv

   This will create a virtual environment named "myenv" in the current directory.

4. Activate the virtual environment: To activate the virtual environment, run the following command:

   myenv\Scripts\activate

   You will notice that the command prompt changes to show the name of your virtual environment.

5. Install Flask: With the virtual environment activated, you can now install Flask. Run the following command:

   pip install flask

   This will download and install Flask and its dependencies.

6. Verify the installation: Once the installation is complete, you can verify that Flask is installed correctly. Run the following command:

   python -c "import flask; print(flask.__version__)"

   If Flask is installed properly, you should see the version number printed in the command prompt.

That's it! Flask should now be installed in your virtual environment on Windows. You can start building your Flask applications by writing your Python code in a file with a `.py` extension and running it using the `python` command within the virtual environment. Remember to activate the virtual environment each time you work on your Flask project by running the activation command mentioned in step 4.


To install Flask on Windows without a virtual environment, you can follow these steps:

If you're receiving a `ModuleNotFoundError` for the 'flask' module, it means that Flask is not installed in your Python environment. To resolve this issue, you can follow these steps:

1. Ensure you have Python installed: Verify that Python is installed on your system by opening a command prompt and running the command `python --version`. If Python is installed, it will display the version number. If not, download and install Python from the official website: https://www.python.org/downloads/

2. Install Flask: Open a command prompt and run the following command to install Flask using pip:

   pip install flask

   Make sure to run this command with administrative privileges if required. Pip is a package manager for Python, and it will download and install Flask and its dependencies.

3. Verify the installation: After the installation completes, you can verify if Flask is installed correctly. In the command prompt, run the following command:

   python -c "import flask; print(flask.__version__)"

   If Flask is installed properly, it should print the version number without any errors.

Once Flask is successfully installed, you should be able to run your Flask application without encountering the `ModuleNotFoundError`.


Here's a simple "Hello, World!" example using Flask in Python:


from flask import Flask

# Create a Flask application
app = Flask(__name__)

# Define a route and its corresponding function
@app.route('/')
def hello_world():
    return 'Hello, World!'

# Run the Flask application
if __name__ == '__main__':
    app.run()


Save the above code in a file with a `.py` extension, such as `app.py`. Make sure you have Flask installed in your Python environment as described in the previous instructions. Then, you can run the script from the command line using `python app.py`.

The Flask application creates an instance of the Flask class and defines a single route `'/'` using the `@app.route` decorator. The function `hello_world()` is associated with this route and returns the string `'Hello, World!'`.

When you run the script, the Flask development server starts, and you can access the application by visiting `http://localhost:5000` in your web browser. The page should display "Hello, World!" as the response.

Remember to stop the server by pressing `Ctrl+C` in the command prompt when you're done testing the application.


 * Serving Flask app 'app'

 * Debug mode: off

WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.

 * Running on http://127.0.0.1:5000

Press CTRL+C to quit

127.0.0.1 - - [21/Jun/2023 11:49:15] "GET / HTTP/1.1" 200 -

127.0.0.1 - - [21/Jun/2023 11:49:15] "GET /favicon.ico HTTP/1.1" 404 -


The Debug mode is enabled by setting the debug property of the application object to True before running or passing the debug parameter to the run() method.

app.debug = True

app.run()

app.run(debug = True)


route() decorator in Flask is used to bind URL to a function. For example −

@app.route(‘/hello’)
def hello_world():
   return hello world


The add_url_rule() function of an application object is also available to bind a URL with a function as in the above example, route() is used.

A decorator’s purpose is also served by the following representation −

def hello_world():
   return hello world
app.add_url_rule(‘/’, hello’, hello_world)


In the following example, the rule parameter of route() decorator contains <name> variable part attached to URL ‘/hello’. Hence, if the http://localhost:5000/hello/ITClass is entered as a URL in the browser, ‘ITClass’ will be supplied to hello() function as argument.

from flask import Flask
app = Flask(__name__)

@app.route('/hello/<name>')
def hello_name(name):
   return 'Hello %s!' % name

if __name__ == '__main__':
   app.run(debug = True)

Save the above script as hello.py and run it from Python shell. Next, open the browser and enter URL http://localhost:5000/hello/ITClass.

The following output will be displayed in the browser.

Hello ITClass!


In addition to the default string variable part, rules can be constructed using the following converters −

Sr.No.Converters & Description
1

int   accepts integer

2

float  For floating point value

3

path   accepts slashes used as directory separator character

In the following code, all these constructors are used.

from flask import Flask
app = Flask(__name__)

@app.route('/blog/<int:postID>')
def show_blog(postID):
   return 'Blog Number %d' % postID

@app.route('/rev/<float:revNo>')
def revision(revNo):
   return 'Revision Number %f' % revNo

if __name__ == '__main__':
   app.run()


The url_for() function is very useful for dynamically building a URL for a specific function. The function accepts the name of a function as first argument, and one or more keyword arguments, each corresponding to the variable part of URL.

The following script demonstrates use of url_for() function.

from flask import Flask, redirect, url_for
app = Flask(__name__)

@app.route('/admin')
def hello_admin():
   return 'Hello Admin'

@app.route('/guest/<guest>')
def hello_guest(guest):
   return 'Hello %s as Guest' % guest

@app.route('/user/<name>')
def hello_user(name):
   if name =='admin':
      return redirect(url_for('hello_admin'))
   else:
      return redirect(url_for('hello_guest',guest = name))

if __name__ == '__main__':
   app.run(debug = True)

Http protocol is the foundation of data communication in world wide web. Different methods of data retrieval from specified URL are defined in this protocol.

The following table summarizes different http methods −

Sr.No.Methods & Description
1

GET

Sends data in unencrypted form to the server. Most common method.

2

HEAD

Same as GET, but without response body

3

POST

Used to send HTML form data to server. Data received by POST method is not cached by server.

4

PUT

Replaces all current representations of the target resource with the uploaded content.

5

DELETE

Removes all current representations of the target resource given by a URL

By default, the Flask route responds to the GET requests. However, this preference can be altered by providing methods argument to route() decorator.

In order to demonstrate the use of POST method in URL routing, first let us create an HTML form and use the POST method to send form data to a URL.

Save the following script as login.html

<html>
   <body>
      <form action = "http://localhost:5000/login" method = "post">
         <p>Enter Name:</p>
         <p><input type = "text" name = "nm" /></p>
         <p><input type = "submit" value = "submit" /></p>
      </form>
   </body>
</html>

Now enter the following script in Python shell.

from flask import Flask, redirect, url_for, request
app = Flask(__name__)

@app.route('/success/<name>')
def success(name):
   return 'welcome %s' % name

@app.route('/login',methods = ['POST', 'GET'])
def login():
   if request.method == 'POST':
      user = request.form['nm']
      return redirect(url_for('success',name = user))
   else:
      user = request.args.get('nm')
      return redirect(url_for('success',name = user))

if __name__ == '__main__':
   app.run(debug = True)

After the development server starts running, open login.html in the browser, enter name in the text field and click Submit.



Flask will try to find the HTML file in the templates folder, in the same folder in which this script is present.

  • Application folder
    • Hello.py
    • templates
      • hello.html

The term ‘web templating system’ refers to designing an HTML script in which the variable data can be inserted dynamically. A web template system comprises of a template engine, some kind of data source and a template processor.

The following code is saved as hello.html in the templates folder.

<!doctype html>
<html>
   <body>
   
      <h1>Hello {{ name }}!</h1>
      
   </body>
</html>

Next, run the following script from Python shell.

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/hello/<user>')
def hello_name(user):
   return render_template('hello.html', name = user)

if __name__ == '__main__':
   app.run(debug = True)

As the development server starts running, open the browser and enter URL as − http://localhost:5000/hello/mvl

The variable part of URL is inserted at {{ name }} place holder.

The jinja2 template engine uses the following delimiters for escaping from HTML.

  • {% ... %} for Statements
  • {{ ... }} for Expressions to print to the template output
  • {# ... #} for Comments not included in the template output
  • # ... ## for Line Statements

The Python Script is as follows −

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/hello/<int:score>')
def hello_name(score):
   return render_template('hello.html', marks = score)

if __name__ == '__main__':
   app.run(debug = True)

HTML template script of hello.html is as follows −

<!doctype html>
<html>
   <body>
      {% if marks>50 %}
         <h1> Your result is pass!</h1>
      {% else %}
         <h1>Your result is fail</h1>
      {% endif %}
   </body>
</html>

Note that the conditional statements if-else and endif are enclosed in delimiter {%..%}.


from static folder in your package or next to your module and it will be available at /static on the application.

A special endpoint ‘static’ is used to generate URL for static files.

In the following example, a javascript function defined in hello.js is called on OnClick event of HTML button in index.html, which is rendered on ‘/’ URL of the Flask application.

from flask import Flask, render_template
app = Flask(__name__)

@app.route("/")
def index():
   return render_template("index.html")

if __name__ == '__main__':
   app.run(debug = True)

The HTML script of index.html is given below.

<html>
   <head>
      <script type = "text/javascript" 
         src = "{{ url_for('static', filename = 'hello.js') }}" ></script>
   </head>
   
   <body>
      <input type = "button" onclick = "sayHello()" value = "Say Hello" />
   </body>
</html>

hello.js contains sayHello() function.

function sayHello() {
   alert("Hello World")
}
  • Form − It is a dictionary object containing key and value pairs of form parameters and their values.

  • args − parsed contents of query string which is part of URL after question mark (?).

  • Cookies − dictionary object holding Cookie names and values.

  • files − data pertaining to uploaded file.

  • method − current request method.

-------------------------------

In the following example, ‘/’ URL renders a web page (student.html) which has a form. The data filled in it is posted to the ‘/result’ URL which triggers the result() function.

The results() function collects form data present in request.form in a dictionary object and sends it for rendering to result.html.

The template dynamically renders an HTML table of form data.

Given below is the Python code of application −

from flask import Flask, render_template, request
app = Flask(__name__)

@app.route('/')
def student():
   return render_template('student.html')

@app.route('/result',methods = ['POST', 'GET'])
def result():
   if request.method == 'POST':
      result = request.form
      return render_template("result.html",result = result)

if __name__ == '__main__':
   app.run(debug = True)

Given below is the HTML script of student.html.

<html>
   <body>
      <form action = "http://localhost:5000/result" method = "POST">
         <p>Name <input type = "text" name = "Name" /></p>
         <p>Physics <input type = "text" name = "Physics" /></p>
         <p>Chemistry <input type = "text" name = "chemistry" /></p>
         <p>Maths <input type ="text" name = "Mathematics" /></p>
         <p><input type = "submit" value = "submit" /></p>
      </form>
   </body>
</html>

Code of template (result.html) is given below −

<!doctype html>
<html>
   <body>
      <table border = 1>
         {% for key, value in result.items() %}
            <tr>
               <th> {{ key }} </th>
               <td> {{ value }} </td>
            </tr>
         {% endfor %}
      </table>
   </body>
</html>

Run the Python script and enter the URL http://localhost:5000/ in the browser

------



More ref https://www.tutorialspoint.com/flask/

For more guidance on Projects !!!

Online Individual / Group classes in English / Sinhala / Tamil. Sample Projects/Assignments Exam Papers, Tutorials, Notes and Answers & more ..

CALL +94 777 33 7279 | EMAIL  ITCLASSSL@GMAIL.COM

No comments:

Post a Comment

Oracle OCI AI Foundations AI ML Student Final Year Projects and Guidance Python

  Notes 🤖 Generative AI for Beginners 🤖 OCI 2024 AI Foundations Course Introduction 🤖 Introduction (AI) (AGI) 🤖 AI Tasks and Data 🤖 Dem...