Creating a Virtual Python Environment
Do the following tasks:
Task 1 : Set up the Environment
- Once the virtual server is provided, click `Run --> Install` to install the required dependencies.
Task 2 : Create a Virtual Environment
- Open a new terminal by clicking 'File ---> New Terminal'.
- Create a virtual environment named 'myprojectenv'.
Hint: Use 'virtualenv'.
- Activate the virtual environment 'myprojectenv'.
Hint: Use the 'source' command.
- Install the flask module in the activated virtual environment. Hint: Use 'pip' command to install the 'flask' module.
- Exit from the virtual environment 'myprojectenv'.
Hint: Use the 'deactiavte' command.
Task 3: Verify the Virtual Environment
- Verify if the virtual environment 'myprojectenv' is successfully created or not by clicking `Run -> Test`.
Task 4: Submit the Solution
- After successful verification of the virtual environment, submit the solution by clicking the 'Submit' button.
Git Instructions
Use the following commands to work with this project
echo start
bash .test.sh
python -m pip install --user --upgrade pip
Solution
python -m virtualenv myprojectenv
source myprojectenv/bin/activate
pip install flask
deactivate
Creating a Basic Flask Application
Do the following tasks:
Task 1 : Set up the Environment
- Once the virtual server is provided, click `Run -> Install` to install the required dependencies.
Task 2 : Create a Basic Flask Application
- After setting up the environment, open the file 'helloapp/hello.py' and follow the instructions specified in it.
- Create a flask application named 'app'.
- Define a view function named 'hello' which returns the string "Hello World!!! I've run my first Flask application."
- Ensure that the view function 'hello' is routed when a user accesses the URL '/'.
- Run the application at 0.0.0.0 and port 8000.
Task 3: View the Application
- After creating the application, you can access the application by clicking `Run -> Run Server`. A 'PreviewApp' button appears.
- Click PreviewApp to open the home page of the flask application in the HackerRank browser.
- If you are not able to view the application in the HackerRank browser, copy and paste the home page URL in your local browser. The home page of the Flask application appears.
Task 4: Test the Application
- Test the application by clicking 'Run -> Test'.
- The number of test cases defined in `helloapp/tests.py` that have passed are displayed.
- If any test case has failed, modify the contents of 'helloapp/hello.py' and ensure that all test cases pass.
Task 4: Submit the Solution
- Once all test cases have passed, submit the solution to HackerRank by clicking 'Submit'.
Git Instructions
Use the following commands to work with this project
python3 helloapp/hello.py
py.test helloapp/tests.py
python3 -m pip install --user --upgrade pip; pip3 install --user -r requirements.txt
Solution
from flask import Flask
## Define a flask application name 'app' below
app = Flask(__name__)
## Define below a view function 'hello', which displays the message
## "Hello World!!! I've run my first Flask application."
@app.route('/')
def hello():
return "Hello World!!! I've run my first Flask application."
## Write the required code below which runs flask applictaion 'app' defined above
## on host 0.0.0.0 and port 8000
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8000)
Writing View Functions in Flask
Do the following tasks:
Task 1 : Set up the Environment
- Once the virtual server is provided, click `Run -> Install` to install the required dependencies.
Task 2 : Create a Basic Flask Application
- After setting up the environment, open the file 'helloapp/hello.py' and follow the instructions specified in it.
- Create a flask application named 'app'.
Task 3 : Define 'hello' View Function
- Define a view function named 'hello' which returns the string "Hello World!!! I've run my first Flask application."
- Ensure that the view function 'hello' is routed when a user accesses the URL '/' .
Task 4 : Define 'hello_user' View Function
- Define a view function named 'hello_user' which takes 'username' as an argument, and returns an HTML string containing an 'h2' header "Hello ".
- After displaying the hello message, the HTML string must also display a quote, randomly chosen from the `quotes` list.
- Before displaying the quote, the HTML string must contain the 'h3' header 'Quote of the Day for You'.
- Ensure that the view function 'hello_user' is routed when a user accesses the URL '/hello//'.
Task 5 : Define 'quotes' View Function
- Define a view function named 'display_quotes', which returns an HTML string that displays all the quotes present in the 'quotes' list in an unordered list.
- Before displaying 'quotes' as an unordered list, the HTML string must also include an 'h1' header "Famous Quotes".
- Ensure that the view function 'display_quotes' is routed when a user accesses the URL '/quotes/'.
Task 6 : Launch the Application
- Write a function to launch the application at 0.0.0.0 and port 8000.
Task 7: View the Application
- After creating the application, you can access the application by clicking `Run -> Run Server`. A 'PreviewApp' button appears.
- Click PreviewApp to open the home page of the flask application in the HackerRank browser.
- If you are not able to view the application in the HackerRank browser, copy and paste the home page URL in your local browser. The home page of the Flask application appears.
Task 8: Test the Application
- Test the application by clicking 'Run -> Test'.
- The number of test cases defined in `helloapp/tests.py` that have passed are displayed.
- If any test case has failed, modify the contents of 'helloapp/hello.py' and ensure that all test cases pass.
Task 9: Submit the Solution
- Once all test cases have passed, submit the solution to HackerRank by clicking 'Submit'.
Git Instructions
Use the following commands to work with this project
python3 helloapp/hello.py
py.test helloapp/tests.py
python3 -m pip install --user --upgrade pip; pip3 install --user -r requirements.txt
Solution
from flask import Flask
import random
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!!! I've run my first Flask application."
@app.route("/hello/<username>/")
def hello_user(username):
quotes = [
"Only two things are infinite, the universe and human stupidity, and I am not sure about the former.",
"Give me six hours to chop down a tree and I will spend the first four sharpening the axe.",
"Tell me and I forget. Teach me and I remember. Involve me and I learn.",
"Listen to many, speak to a few.",
"Only when the tide goes out do you discover who has been swimming naked.",
]
return """<h2>Hello {}</h2>
<h3>Quote of the Day for You</h3>
<p>{}</p>""".format(username, random.choice(quotes))
@app.route("/quotes/")
def display_quotes():
quotes = [
"Only two things are infinite, the universe and human stupidity, and I am not sure about the former.",
"Give me six hours to chop down a tree and I will spend the first four sharpening the axe.",
"Tell me and I forget. Teach me and I remember. Involve me and I learn.",
"Listen to many, speak to a few.",
"Only when the tide goes out do you discover who has been swimming naked.",
]
quotes_list = ""
for quote in quotes:
quotes_list += "<li>{}</li>".format(quote)
return """<h1>Famous Quotes</h1>
<ul>
{}
</ul>""".format(quotes_list)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)
Using Templates in Flask
Do the following tasks:
Task 1 : Set up the Environment
- Once the virtual server is provided, click `Run -> Install` to install the required dependencies.
Task 2 : Create a Basic Flask Application
- After setting up the environment, open the file 'helloapp/hello.py' and follow the instructions specified in it.
- Create a flask application named 'app'.
Task 3 : Define 'hello' View Function
- Define a view function named 'hello' which returns the string "Hello World!!! I've run my first Flask application."
Ensure that the view function 'hello' is routed when a user accesses the URL '/' .
Ensure that the view function 'hello' renders the template 'index.hmtl'.
Hint: Create 'index.html' inside the 'templates' folder.
Task 4 : Define 'hello_user' View Function
- Define a view function named 'hello_user' which takes 'username' as an argument, and returns an HTML string containing an 'h2' header "Hello ".
- After displaying the hello message, the HTML string must also display a quote, randomly chosen from the `quotes` list.
- Before displaying the quote, the HTML string must contain the 'h3' header 'Quote of the Day for You'.
- Ensure that the view function 'hello_user' is routed when a user accesses the URL '/hello//'.
- Ensure that the view function 'hello_user' renders the template 'hello_user.hmtl'.
Hint: Create 'hello_user.html' inside the 'templates' folder.
Task 5 : Define 'quotes' View Function
- Define a view function named 'display_quotes', which returns an HTML string that displays all the quotes present in the 'quotes' list in an unordered list.
- Before displaying 'quotes' as an unordered list, the HTML string must also include an 'h1' header "Famous Quotes".
- Ensure that the view function 'display_quotes' is routed when a user accesses the URL '/quotes/'.
- Ensure that the view function 'quotes' renders the template 'quotes.hmtl'.
Hint: Create 'quotes.html' inside the 'templates' folder.
Task 6 : Launch the Application
- Write a function to launch the application at 0.0.0.0 and port 8000.
Task 7: View the Application
- After creating the application, you can access the application by clicking `Run -> Run Server`. A 'PreviewApp' button appears.
- Click PreviewApp to open the home page of the flask application in the HackerRank browser.
- If you are not able to view the application in the HackerRank browser, copy and paste the home page URL in your local browser. The home page of the Flask application appears.
Task 8: Test the Application
- Test the application by clicking 'Run -> Test'.
- The number of test cases defined in `helloapp/tests.py` that have passed are displayed.
- If any test case has failed, modify the contents of 'helloapp/hello.py' and ensure that all test cases pass.
Task 9: Submit the Solution
- Once all test cases have passed, submit the solution to HackerRank by clicking 'Submit'.
Git Instructions
Use the following commands to work with this project
python3 helloapp/hello.py
py.test helloapp/tests.py
python3 -m pip install --user --upgrade pip; pip3 install --user -r requirements.txt
Solution
from flask import Flask, render_template
import random
app = Flask(__name__)
@app.route("/")
def hello():
return render_template("index.html")
@app.route("/hello/<username>/")
def hello_user(username):
quotes = [
"Only two things are infinite, the universe and human stupidity, and I'm not sure about the former.",
"Give me six hours to chop down a tree and I will spend the first four sharpening the axe.",
"Tell me and I forget. Teach me and I remember. Involve me and I learn.",
"Listen to many, speak to a few.",
"Only when the tide goes out do you discover who's been swimming naked."
]
return render_template("hello_user.html", username=username, quote=random.choice(quotes))
@app.route("/quotes/")
def display_quotes():
quotes = [
"Only two things are infinite, the universe and human stupidity, and I'm not sure about the former.",
"Give me six hours to chop down a tree and I will spend the first four sharpening the axe.",
"Tell me and I forget. Teach me and I remember. Involve me and I learn.",
"Listen to many, speak to a few.",
"Only when the tide goes out do you discover who's been swimming naked."
]
return render_template("quotes.html", quotes=quotes)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)
Defining Models in Flask
Do the following tasks:
Task 1 : Set up the Environment
- Once the virtual server is provided, click `Run -> Install` to install the required dependencies.
Task 2 : Define 'Quotes' Model
- After setting up the environment, define the 'Quotes' model in 'helloapp/models.py'.
- The model must contain three columns named 'id', 'quoteauthor', and 'quotestring'.
- 'id' must be an integer and primary key.
- 'quoteauthor' must be a string of max 100 characters.
- 'quotestring' must be a string of max 200 characters.
- Define the method '__repr__' which displays a quote object as '
'
.
- Perform database migrations, and insert data in the 'quotes' database from the backend.
Task 3 : Define 'hello' View Function in 'helloapp/routes.py'
- Define a view function named 'hello' which returns the string "Hello World!!! I've run my first Flask application."
- Ensure that the view function 'hello' is routed when a user accesses the URL '/'.
- Ensure that the view function 'hello' renders the template 'index.hmtl'.
Hint: Create 'index.html' inside the 'templates' folder.
Task 4 : Define 'hello_user' View Function in 'helloapp/routes.py'
- Define a view function named 'hello_user' which takes 'username' as an argument, and returns an HTML string containing an 'h2' header "Hello ".
- After displaying the hello message, the HTML string must also display a quote, randomly chosen from the `quotes` list in `hello.db'.
- Before displaying the quote, the HTML string must contain the 'h3' header 'Quote of the Day for You'.
- Ensure that the view function 'hello_user' is routed when a user accesses the URL '/hello//'.
- Ensure that the view function 'hello_user' renders the template 'hello_user.hmtl'.
Hint: Create 'hello_user.html' inside the 'templates' folder.
Task 5 : Define 'quotes' View Function in 'helloapp/routes.py'
- Define a view function named 'display_quotes', which returns an HTML string that displays all the quotes present in the 'quotes' list in an unordered list.
- Before displaying 'quotes' as an unordered list, the HTML string must also include an 'h1' header "Famous Quotes".
Ensure that the view function 'display_quotes' is routed when a user accesses the URL '/quotes/'.
Ensure that the view function 'quotes' renders the template 'quotes.hmtl'.
Hint: Create 'quotes.html' inside the 'templates' folder.
Task 6: View the Application
- After creating the application, you can access the application by clicking `Run -> Run Server`. A 'PreviewApp' button appears.
- Click PreviewApp to open the home page of the flask application in the HackerRank browser.
- If you are not able to view the application in the HackerRank browser, copy and paste the home page URL in your local browser. The home page of the Flask application appears.
Task 7: Test the Application
- Test the application by clicking 'Run -> Test'.
- The number of test cases defined in `helloapp/tests.py` that have passed are displayed.
- If any test case has failed, modify the contents of 'helloapp/hello.py' and ensure that all test cases pass.
Task 8: Submit the Solution
- Once all test cases have passed, submit the solution to HackerRank by clicking 'Submit'.
Git Instructions
Use the following commands to work with this project
export LC_ALL=C.UTF-8; export LANG=C.UTF-8; export FLASK_APP=main.py; flask run --host 0.0.0.0 --port 8000
py.test helloapp/tests.py
python3 -m pip install --user --upgrade pip; pip3 install --user -r requirements.txt
Solution
helloapp/models.py
from helloapp import db
# Define Quotes model below
class Quotes(db.Model):
id = db.Column(db.Integer, primary_key=True)
quoteauthor = db.Column(db.String(100))
quotestring = db.Column(db.String(100))
def __repr__(self):
return "<Quote : [{}]>".format(self.quotestring)
helloapp/routes.py
from flask import render_template
import random
from .models import Quotes
from helloapp import app, db
## Define below a view function 'hello', which displays the message
## "Hello World!!! I've run my first Flask application."
## The view function 'hello' should be mapped to URL '/' .
## The view function must render the template 'index.html'
@app.route('/')
def hello():
return render_template('index.html')
## Define below a view function 'hello_user', which takes 'username' as an argument
## and returns the html string containing a 'h2' header "Hello <username>"
## After displaying the hello message, the html string must also display one quote,
## randomly chosen from the provided list `quotes`
## Before displaying the quote, the html string must contain the 'h3' header 'Quote of the Day for You'
## The view function 'hello_user' should be mapped to URL '/hello/<username>/' .
## The view function must render the template 'hello_user.html'
## Use the below list 'quotes' in 'hello_user' function
## quotes = [
## "Only two things are infinite, the universe and human stupidity, and I'm not sure about the former.",
## "Give me six hours to chop down a tree and I will spend the first four sharpening the axe.",
## "Tell me and I forget. Teach me and I remember. Involve me and I learn.",
## "Listen to many, speak to a few.",
## "Only when the tide goes out do you discover who's been swimming naked."
## ]
@app.route('/hello/<username>/')
def hello_user(username):
quotes = Quotes.query.all()
return render_template('hello_user.html', username=username, quote=random.choice(quotes))
## Define below a view function 'display_quotes', which returns an html string
## that displays all the quotes present in 'quotes' list in a unordered list.
## Before displaying 'quotes' as an unordered list, the html string must also include a 'h1' header "Famous Quotes".
## The view function 'display_quotes' should be mapped to URL '/quotes/' .
## The view function must render the template 'quotes.html'
## Use the below list 'quotes' in 'display_quotes' function
## quotes = [
## "Only two things are infinite, the universe and human stupidity, and I'm not sure about the former.",
## "Give me six hours to chop down a tree and I will spend the first four sharpening the axe.",
## "Tell me and I forget. Teach me and I remember. Involve me and I learn.",
## "Listen to many, speak to a few.",
## "Only when the tide goes out do you discover who's been swimming naked."
## ]
@app.route('/quotes/')
def display_quotes():
quotes = Quotes.query.all()
return render_template("quotes.html", quotes=quotes)
helloapp/templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Quotes App{%block title %} - Home{%endblock%}</title>
</head>
<body>
{%block content %} - Home{%endblock%}
</body>
</html>
helloapp/templates/index.html
{%extends 'base.html'%}
{%block content%}
<h2>Hello World!!! I've run my first Flask application.</h2>
{%endblock%}
helloapp/templates/quotes.html
{%extends 'base.html'%}
{%block content%}
<h1>Famous Quotes</h1>
<ul>
{% for quote in quotes %}
<li>{{quote.quotestring}} - {{quote.quoteauthor}}</li>
{% endfor %}
</ul>
{%endblock%}
helloapp/templates/hello_user.html
{%extends 'base.html'%}
{%block content%}
<h2>Hello {{username}}</h2>
<h3>Quote of the Day</h3>
<p>{{quote.quotestring}} - {{quote.quoteauthor}}</p>
{%endblock%}
Do the following tasks:
Task 1 : Set up the Environment
- Once the virtual server is provided, click `Run -> Install` to install the required dependencies.
Task 2 : Define 'QuoteForm' class in 'forms.py'
The form must have two text fields named "Quote Author" and "Quote". The corresponding field names must be "qauthor" and "qstring" respectively.
The form must have a Submit button with value "Add Quote".
- Include the following validations of both the text fields:
- The length of the input string "Quote Author" must be between 3 and 100, and must display the message "[Field must be between 3 and 100 characters long.]" to the user.
- If the "Quote Author" field has a null value, the message "[This field is required.]" must be displayed to the user.
- The length of "Quote" must be between 3 and 200, and must display the message "[Field must be between 3 and 200 characters long.]" to the user.
- If the "Quote" field has a null value, the message "[This field is required.]" must be displayed to the user.
Task 3 : Define 'addquote.html' Template in 'helloapp/templates' Folder
- Define the template 'addquote.html' which takes the instance of the 'QuoteForm' as an input, and displays it to the user.
- It must also display errors (if any).
Task 4 : Define 'addquote' View Function in 'helloapp/routes.py'
- Define a view function named 'addquote' which renders the template 'addquote.html', and then displays the above defined QuoteForm.
- The form must take a quote string and it's author as input, and submit it to the server.
- If the data is valid, it must be inserted in the 'quotes' table.
- Finally, it must render 'addquote_confirmation.html' after successful submission of data.
- If a wrong input is found, the function must render the 'addquote.html' template, highlighting the wrong input fields.
- Ensure that the view function 'addquote.html' is routed when a user accesses the URL '/addquote/'.
Task 5: View the Application
- After creating the application, you can access the application by clicking `Run -> Run Server`. A 'PreviewApp' button appears.
- Click PreviewApp to open the home page of the flask application in the HackerRank browser.
- If you are not able to view the application in the HackerRank browser, copy and paste the home page URL in your local browser. The home page of the Flask application appears.
Task 6: Add and View Quotes
- Access the page '/addquote/', and add a quote.
- View all quotes by accessing the page '/quotes/'.
Task 7: Test the Application
- Test the application by clicking 'Run -> Test'.
- The number of test cases defined in `helloapp/tests.py` that have passed are displayed.
- If any test case has failed, modify the contents of 'helloapp/hello.py' and ensure that all test cases pass.
Task 8: Submit the Solution
- Once all test cases have passed, submit the solution to HackerRank by clicking 'Submit'.
Git Instructions
Use the following commands to work with this project
export LC_ALL=C.UTF-8; export LANG=C.UTF-8; export FLASK_APP=main.py; flask run --host 0.0.0.0 --port 8000
py.test helloapp/tests.py
python3 -m pip install --user --upgrade pip; pip3 install --user -r requirements.txt
Solution
helloapp/routes.py
from flask import render_template, request
import random
from .models import Quotes
from .forms import QuoteForm
from helloapp import app, db
@app.route('/')
def hello():
return render_template('index.html')
@app.route('/hello/<string:username>/')
def hello_user(username):
quotes = Quotes.query.all()
quotes = [quote.quotestring for quote in quotes]
random_quote = random.choice(quotes)
return render_template('hello_user.html', username=username, quote=random_quote)
@app.route('/quotes/')
def display_quotes():
quotes = Quotes.query.all()
quotes = [quote.quotestring for quote in quotes]
return render_template('quotes.html', quotes=quotes)
@app.route('/addquote/', methods=['GET', 'POST'])
def add_quote():
form = QuoteForm()
if request.method == 'POST' and form.validate_on_submit():
quote = Quotes(quoteauthor=form.qauthor.data,
quotestring=form.qstring.data)
try:
db.session.add(quote)
db.session.commit()
except Exception:
db.session.rollback()
return render_template("addquote_confirmation.html", title="Quote Added")
return render_template("addquote.html", form=form, title="Add Quote")
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, validators
class QuoteForm(FlaskForm):
qauthor = StringField("Quote Author", validators=[validators.Length(3, 100), validators.DataRequired()])
qstring = StringField("Quote", validators=[validators.Length(3, 200), validators.DataRequired()])
submit = SubmitField("AddQuote")
helloapp/templates/addquote.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{title}}</title>
</head>
<body>
<h2>Quote Form</h2>
<form action="" method="post">
{{form.csrf_token}}
{{ form.qauthor.label }} : {{ form.qauthor }} <br><br>
{% for error in form.qauthor.errors %}
<span style="color: red;">[{{ error }}]</span><br>
{% endfor %}
<br>
{{ form.qstring.label }} : {{ form.qstring }} <br><br>
{% for error in form.qstring.errors %}
<span style="color: red;">[{{ error }}]</span><br>
{% endfor %}
<br>
{{ form.submit }}
</form>
</body>
</html>