PySpark || Fresco Play || 58339

Pyspark - Creating Dataframe

In this hands-on, you will start working on PySpark basics. Follow the below instructions to complete the hands-on:

STEPS:

Step 1: Import the SparkSession package.

Step 2: Create a SparkSession object.

Step 3: Create a DataFrame using SparkSession object, and display the DataFrame.

Step4: Create a simple passenger instance with 4 fields, Name, age, source, destination.

Step5: Create 2 passenger fields with following values

  • David , 22, London, Paris
  • Steve, 22, New York , Sydney

Step 6: Display the DataFrame to check the data.

NOTE:

Don't edit the line at the bottom of the answer.py file which will save the created DataFrame into a file.

Steps to complete the Handson:

1. Install all the necessary dependencies using the INSTALL option from the Project menu.

2. Run your solution using the RUN -> Run option.

3. Run the tests to check using the TEST option from the Project menu.

#IMP : In order to execute your code in answer.py file, please open a new terminal and use the command "spark-submit answer.py"

Git Instructions

Use the following commands to work with this project

spark-submit answer.py

spark-submit score.py

echo "Installation not needed"

Solution

from pyspark.sql import SparkSession, Row

sc = SparkSession.builder.appName("Example App").getOrCreate()
Passenger = Row("Name", "age", "source", "destination")
p1 = Passenger("David" , 22, "London", "Paris")
p2 = Passenger("Steve", 22, "New York", "Sydney")
passData = [p1, p2]
df = sc.createDataFrame(passData)
df.show()
# Don't Remove this line 
df.coalesce(1).write.parquet("PassengerData")

Reading files in PySpark

In this hands-on, you will start working on PySpark basics. Follow the below instructions to complete the hands-on:

STEPS:

Step 1: Import the SparkSession package.

Step 2: Create a SparkSession object.

Step 3: Read the json file, and create a DataFrame with the json data. Display the DataFrame. Save the DataFrame to a parquet file with name Employees.

Step 4: From the DataFrame, display the associates who are mapped to `JAVA` stream. Save the resultant DataFrame to a parquet file with name JavaEmployees.

NOTE:

1. Use coalesce to store the data frame as a single partition.

2. Ensure to use the exact naming convention for the result folders.

Steps to complete the Handson:

1. Run your solution using the RUN option from Project menu.

2. Run the tests to check using the TEST option from the Project menu.

Git Instructions

Use the following commands to work with this project

spark-submit answer.py

spark-submit score.py

echo "No need to install"

Solution

# Put your code here
from pyspark.sql import SparkSession

sc = SparkSession.builder.appName("Example App").getOrCreate()
df = sc.read.load("emp.json", format="json")

df.show(2)
df.coalesce(1).write.parquet("Employees")

df_java = df.filter(df.stream == 'JAVA')
df_java.coalesce(1).write.parquet("JavaEmployees")

Statistical and Mathematical Functions with DataFrames in Apache Spark

In this hands-on, you will start working on PySpark basics. Follow the below instructions to complete the hands-on:

STEPS:

Step 1: Import the pyspark and SparkSession package.

Step 2: Create a SparkSession object.

Step 3: Create 10 random values as a column and name the column as rand1

Step 4: Create another 10 random values as column and name the column as rand2.

Step 4: Calculate the co-variance and correlation between these two columns.

Step5: Create a new Dataframe with Header names as "Stats" and "Value"

Step6: Fill the new Dataframe with the obtained values as "Co-variance" and "Correlation"

Step7: Save the resultant DataFrame to a CSV file with name Result

NOTE:

1. Use coalesce to store the data frame as a single partition.

2. Ensure to use the exact naming convention for the result files.

Steps to complete the Handson:

1. Run your solution using the RUN option from Project menu.

2. Run the tests to check using the TEST option from the Project menu.

#IMP : In order to execute your code in answer.py file, please open a new terminal and use the command "spark-submit answer.py"

Git Instructions

Use the following commands to work with this project

spark-submit answer.py

spark-submit score.py

bash install.sh

Solution

# Put your code here
from pyspark.sql import SparkSession, Row
from pyspark.sql.functions import rand

sc = SparkSession.builder.appName("Example App").getOrCreate()
df = sc.range(0, 10).withColumn('rand1', rand(seed=11)).withColumn('rand2', rand(seed=31))

Stat = Row("Stats", "Value")
stat1 = Stat("Co-variance", df.stat.cov('rand1', 'rand2'))
stat2 = Stat("Correlation", df.stat.corr('rand1', 'rand2'))
stat_df = sc.createDataFrame([stat1, stat2])
stat_df.write.csv("Result", header = True)

More operations in PySpark

In this hands-on, you will start working on PySpark basics. Follow the below instructions to complete the hands-on:

STEPS:

Step 1: Import the SparkSession package.

Step 2: Create a SparkSession object.

Step 3: Create a DataFrame with the following details under the headers as "ID", "Name","Age","Area of Interest"

Step 4: Fill the Dataframe with the following data:

  • "1","Jack", 22,"Data Science"
  • "2","Luke", 21,"Data Analytics"
  • "3","Leo", 24,"Micro Services"
  • "4","Mark", 21,"Data Analytics"

Step 5: Use describe method on Age column and observe the statistical parameters and save the data into a parquet file under the folder with name "Age" inside /projects/challenge/.

Step 6: Select the columns ID, Name, and Age, and Name should be in descending order. Save the resultant into a parquet file under the folder with name "NameSorted" inside /projects/challenge/.

NOTE:

1. Use coalesce to store the data frame as a single partition.

2. Ensure to use the exact naming convention for the result folders.

Steps to complete the Handson:

1. Run your solution using the RUN option from Project menu.

2. Run the tests to check using the TEST option from the Project menu.

Git Instructions

Use the following commands to work with this project

spark-submit answer.py

spark-submit score.py

bash install.sh

Solution

from pyspark.sql import SparkSession, Row

sc = SparkSession.builder.appName("Example App").getOrCreate()
Employee = Row("ID", "Name","Age","Area of Interest")
emp1 = Employee("1","Jack", 22,"Data Science")
emp2 = Employee("2","Luke", 21,"Data Analytics")
emp3 = Employee("3","Leo", 24,"Micro Services")
emp4 = Employee("4","Mark", 21,"Data Analytics")
empData = [emp1, emp2, emp3, emp4]
df = sc.createDataFrame(empData)

df.describe("Age").coalesce(1).write.parquet("Age")

df.sort("Name", ascending=False).coalesce(1).write.parquet("NameSorted")
Share:

Flask - Python Web Framework || Fresco Play || 57963

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

# 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."
# The view function 'hello' should be mapped to URL '/' .
@app.route("/")
def hello():
    return "Hello World!!! I've run my first Flask application."


# 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>/' .
# Use the below list 'quotes' in 'hello_user'  function
# 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."
# ]
@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))


# 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/' .
# Use the below list 'quotes' in 'display_quotes'  function
# 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."
# ]
@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)


# 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)

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

# 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."
# 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 = [
        "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))


# 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 = [
        "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)


# 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)

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%}

Creating Web Forms 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 '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)

# Define below a view function 'add_quote', which renders 'addquote.html' template that displays the form , QuoteForm
# The form takes a quote and it's author information and submit's it to server.
# The server process the input data and if found valid, the data is inserted into quotes table.
# and finally renders 'addquote_confirmation.html' template.
# In case if any error is found in input, it renders 'addquote.html' template highlighting errors.
# that displays all the quotes present in 'quotes' list in a unordered list.


@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")

helloapp/forms.py

from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, validators

# Define QuoteForm below
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>
Share:

Python FSP - Mini-Project - Sprint7 - Capstone Project - WebFramework || Fresco Play || 72113

Mini-Project - Python FSP - Capstone Project- WebFramework

Instructions

In the Handson env there will be a directory called 'Project' in the Desktop, where you can find the files.

In this challenge, you have to create a blog website in Django application.

Steps:

In models.py, read the instructions and create models.

In forms.py, create form fields as per instructions given in py file.

In views.py, create the following endpoints

  • signup - use 'signup/' route and redirect to login page after successful signup.
  • login - use 'login/' route and redirect to index page after successful login. If the username and password doesn't match show a message as ' incorrect username or password'
  • create - use 'create/' route. On this page user enter blog title and content after successful creation of blog redirect to index page.
  • index - use 'index/' route and this page shows all the blog created by the user. only registered user can view into this page.
  • blog - use 'index/blog/<int:id>/' route. This page display full content of the blog. only registered user can view into this page.

Create html files in the templates folder for these above endpoints.

In urls.py, add these above endpoints with URI and name.

css files are optional

Note: Once you have completed the django application then add and commit the changes to the local git in the directory where the django application resides.

Do not change or modify the test.py and settings.py file.

Jenkins is already installed and you can just run Jenkins by opening chrome and going to (http://localhost:8080)

Configure Jenkins to integrate with Django application

  1. Login to Jenkins with username as admin and fetch password from the path
     $ cat /var/lib/jenkins/secrets/initialAdminPassword
    
  2. Create a freestyle project named Blog in Jenkins.
  3. Configure the source code of your job with Repository URL file:////home/labuser/Desktop/Project/fullstackdev-capstone
  4. In the Add build step, select execute shell and follow the below format to execute the django application,
     # Add the following command in the shell :
     BUILD_ID=dontkillme
     # write a command to install all the dependencies required for the django application
     pip3 install --user -r requirements.txt
     # write a command to migrate the application
     python3 manage.py makemigrations && python3 manage.py migrate --run-syncdb
     # write a command to run the django application in 0.0.0.0:8001 port in background.
     python3 manage.py runserver 0.0.0.0:8001
     # write a command to test the django application
     python3 manage.py test
    
  5. Apply the changes and build your job.
  6. Check your result in console output.
  7. You are done if your console output is Finished: SUCCESS

Solution

  • models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
# from django.core.validators import RegexValidator
"""

create user model
    firstname - textfield
    lastname  - textfield
    username  - textfield must be unique
    email     - emailfield primarykey
    dob       - datefield
    my_photo  - imagefield(optional)

create Blog model
    title     - textfield
    content   - textfield
    created_at- datefield
    blog_photo- imagefield(optional)
    blogger   - manytoone(ForeignKey Field) relationship with user table.

"""


class User(AbstractBaseUser):
    firstname = models.CharField(max_length=100)
    lastname = models.CharField(max_length=100)
    username = models.CharField(max_length=100, unique=True)
    email = models.EmailField(primary_key=True)
    dob = models.DateField()
    my_photo = models.ImageField(upload_to="my_photo", blank=True, null=True)
    # password_validator = RegexValidator(
    #     regex=r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{6,}$", message="Enter a valid password"
    # )
    password = models.CharField(max_length=128)

    USERNAME_FIELD = "username"
    REQUIRED_FIELDS = ["email"]

    def __str__(self):
        return self.username


class Blog(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    created_at = models.DateField()
    blog_photo = models.ImageField(upload_to="blog_photo", blank=True, null=True)
    blogger = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title
  • forms.py
from django import forms
from .models import User, Blog

"""
create loginform with username and password fields
create signupform with the fields matching user model 
create blogform with the fields matching blog model
"""


class loginForm(forms.Form):
    # fields - username, password
    username = forms.CharField(max_length=128)
    password = forms.CharField(widget=forms.PasswordInput)


class signUpForm(forms.ModelForm):
    # fields - firstname, lastname, username, email, password, confirm, dob, my_photo (optional)
    password = forms.CharField(widget=forms.PasswordInput)
    confirm = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ["firstname", "lastname", "username", "email", "dob", "my_photo"]
        widgets = {
            "dob": forms.DateInput(attrs={"type": "date"}),
        }

    def clean(self):
        cleaned_data = super().clean()
        password = cleaned_data.get("password")
        confirm = cleaned_data.get("confirm")
        if password and confirm and password != confirm:
            self.add_error("confirm", "Passwords do not match.")
        return cleaned_data


class createBlog(forms.ModelForm):
    # fields - title, content, img (optional)
    class Meta:
        model = Blog
        fields = ["title", "content", "blog_photo"]
        widgets = {
            "blog_photo": forms.ClearableFileInput(),
        }
  • views.py
from rest_framework.views import View
from django.forms import ValidationError
from django.shortcuts import render, redirect, get_object_or_404
from .forms import loginForm, signUpForm, createBlog
from .models import Blog, User
import datetime


# instructions are given in problem description
def login(request):
    # get method handler render login.html page
    # post method handler authenticate user credentials, create session and redirect to index page
    if request.method == "GET":
        form = loginForm()
        return render(request, "login.html", {"form": form})
    elif request.method == "POST":
        form = loginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data["username"]
            password = form.cleaned_data["password"]
            try:
                user = User.objects.get(username=username)
                if user and user.check_password(password):
                    request.session["user"] = user.email
                    return redirect("index")
                else:
                    form.add_error("username", "Incorrect username or password")
            except User.DoesNotExist:
                form.add_error("username", "Incorrect username or password")
        return render(request, "login.html", {"form": form})


def signup(request):
    # get method handler render signup.html
    # post method handler save the user data and redirects to login page
    #
    if request.method == "GET":
        form = signUpForm()
        return render(request, "signup.html", {"form": form})
    elif request.method == "POST":
        form = signUpForm(request.POST, request.FILES)

        if form.is_valid():
            user = form.save(commit=False)
            user.set_password(form.cleaned_data["password"])
            user.save()
            return redirect("login")

        print(form.errors)
        return render(request, "signup.html", {"form": form})


class create_blog(View):
    # get method handler render create.html
    # post method handler if the create button is clicked, get the title and content field from form, save it and redirect to index page
    def get(self, request):
        if not request.session.get("user"):
            return redirect("login")

        user_email = request.session.get("user")
        user = User.objects.get(email=user_email)

        form = createBlog()
        return render(request, "create.html", {"form": form, "user": user})

    def post(self, request):
        if not request.session.get("user"):
            return redirect("login")

        user_email = request.session.get("user")
        user = User.objects.get(email=user_email)
        form = createBlog(request.POST, request.FILES)
        if form.is_valid():
            blog = form.save(commit=False)
            blog.blogger = user
            blog.created_at = datetime.datetime.now()
            blog.save()
            return redirect("index")
        return render(request, "create.html", {"form": form, "user": user})


def logout(request):
    # get method handler removes the session and redirects to login page
    request.session.flush()
    return redirect("login")


class index(View):
    # get method handler shows the list of blogs render index.html
    def get(self, request):
        user_email = request.session.get("user")
        if not user_email:
            return redirect("login")
        user = User.objects.get(email=user_email)
        blogs = Blog.objects.filter(blogger_id=user_email).order_by("-created_at")
        return render(request, "index.html", {"blogs": blogs, "user": user})


class blog(View):
    # get method handler shows the detailed view of blog rendering blog.html
    def get(self, request, blog_id):
        user_email = request.session.get("user")
        if not user_email:
            return redirect("login")
        user = User.objects.get(email=user_email)
        blog_post = get_object_or_404(Blog, id=blog_id)
        return render(request, "blog.html", {"blog": blog_post, "user": user})
  • urls.py
"""Play URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""

from django.contrib import admin
from django.urls import path
from django.conf.urls.static import static
from .views import login, logout, signup, create_blog, index, blog

urlpatterns = [
    path("admin/", admin.site.urls),
    path("login/", login, name="login"),
    path("signup/", signup, name="signup"),
    path("create/", create_blog.as_view(), name="blog_create"),
    path("index/", index.as_view(), name="index"),
    path("index/blog/<int:blog_id>/", blog.as_view(), name="blog_detail"),
    path("logout/", logout, name="logout"),
]
  • Below are the files in templates

base.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@200,400,600&display=swap" rel="stylesheet" />
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>
      {% block title %}

      {% endblock %}
    </title>
    <style>
      * {
        border-style: none;
        border-radius: 5px;
        padding: 0;
        margin: 0;
      }
      .errorlist {
        list-style: none;
        color: #d43131;
        font-size: small;
      }

      body {
        background-color: #d2fdff;
        font-family: 'Poppins', sans-serif;
        padding: 0%;
        margin: 0%;
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 99vh;
      }

      div {
        padding: 5px;
        margin: 5px;
        display: inline;
      }

      input {
        float: right;
        display: flex;
        align-items: center;
        justify-content: space-around;
        padding: 6px;
      }

      #err {
        display: inline-block;
        right: 10%;
      }

      #card {
        border-radius: 5px;
        padding: 0.5rem;
        display: flex;
        flex-direction: column;
        gap: 1rem;
        justify-content: center;
        align-items: center;
        background-color: #f4bc8a;
        width: 100%;
      }

      #card th,
      .card th {
        text-align: left;
        padding: 0.25rem;
      }

      #card form {
        gap: 0.25rem;
      }

      #card form button {
        margin-top: 0.5rem;
      }

      form {
        display: flex;
        justify-content: center;
        flex-direction: column;
        max-width: 100%;
        width: 600px;
      }

      h2 {
        text-align: center;
        padding-bottom: 0.5rem;
      }

      button,
      .btn {
        /* Spans both columns */
        padding: 10px;
        background-color: #0e9db3;
        color: white;
        border: none;
        font-size: small;
      }

      .nav-bar {
        top: 0;
        position: fixed;
        overflow: hidden;
        z-index: 2;
        margin-top: 0px;
        float: right;
        height: 2em;
        border-radius: 3px;
        width: 100%;
        background-color: white;
        padding: 0.5rem;
        display: flex;
      }
      .nav-bar ul {
        display: flex;
        flex-direction: row;
        gap: 0.5rem;
        list-style-type: none;
        margin: 0;
        padding: 0.5rem;
        overflow: hidden;
      }
      .nav-bar .inline-form {
        margin-left: auto;
      }
      .inline-form {
        display: inline-block;
        width: initial;
      }
      main {
        width: 100vh;
        padding: 0.5rem;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .c {
        display: flex;
        flex-direction: column;
      }
    </style>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  </head>

  <body>
    <header class="nav-bar">
      <ul>
        <li>
          <a href="{% url 'index' %}">Home</a>
        </li>

        {% if user.email is None %}
          <li>
            <a href="{% url 'login' %}">Login</a>
          </li>
          <li>
            <a href="{% url 'signup' %}">Signup</a>
          </li>
        {% else %}
          <li>
            <a href="{% url 'blog_create' %}"> Create +</a>
          </li>
        {% endif %}
      </ul>

      {% if user.email is not None %}
        <form class="inline-form" action="{% url 'logout' %}" method="POST">
          {% csrf_token %}
          <!-- logout button -->
          <button type="submit">Logout</button>
        </form>
      {% endif %}
    </header>
    {% block content %}

    {% endblock %}
  </body>
</html>

index.html

{% extends 'base.html' %}
{% block title %}
  {{ title }}
{% endblock %}

{% block content %}
  <style>
    .bcard {
      border: 1px solid #1f85de;
      display: flex;
      justify-content: center;
      align-items: flex-start;
      flex-direction: column;
      width: 100%;
      max-width: 600px;
    }

    .single {
      display: flex;
      justify-content: space-evenly;
      align-items: stretch;
      margin: 0.5rem;
      background-color: #1f85de;
      color: #fff;
      flex-direction: row;
    }

    main a {
      text-decoration: none;
      color: #fff;
      font-weight: bold;
    }
  </style>
  <!-- write your script to display blog created by current user here -->
  <main class="c">
    {% if blogs %}
      <h2>Here are your blogs:</h2>

      <ul class="bcard">
        {% for blog in blogs %}
          <li class="single">
            <h3><a href="{% url 'blog_detail' blog.id %}">{{ blog.title }}</a></h3>
            <div class="c">
              <p>{{ blog.content|truncatechars:50 }}</p>
              <p>{{ blog.created_at }}</p>
            </div>
          </li>
        {% endfor %}
      </ul>
    {% else %}
      <h2>You have not created any blogs yet.</h2>
    {% endif %}
  </main>
{% endblock %}

blog.html

{%extends 'base.html'%}
{% block title%}
{{blog.title}}
{%endblock%}

{%block content%}
<!-- write your html script to display the all users blog here -->
<main class="c">
    <h2>{{ blog.title }}</h2>
    {% if blog.image %}<img class="blog-image" src="{{ blog.image.url }}" alt="{{ blog.title }}">{% endif %}
    <p>
        <small>Written by: {{ blog.blogger.username }}</small> <br>
        <small>Published on: {{ blog.created_at }}</small>
    </p>
    <div class="content">
        {{ blog.content }}
    </div>
</main>
{%endblock%}

create.html

{% extends 'base.html' %}
{% block title %}
  Create Blog
{% endblock %}

{% block content %}
  <!-- create form in that user can create their blog -->
  <main>
      <form action="{% url 'blog_create' %}" method="POST">
        <h2>Blog Create Form</h2>
      {% csrf_token %}
      <table id="card">{{ form }}</table>
      <button type="submit">Create</button>
    </form>
  </main>
{% endblock %}

login.html

{% extends 'base.html' %}
{% block title %}
  Login
{% endblock %}
{% block content %}
  <!-- create your login form here -->
  <main>
      <form action="{% url 'login' %}" method="POST">
        <h2>Login Form</h2>
      {% csrf_token %}
      <table id="card">{{ form }}</table>
      <button type="submit">Login</button>
    </form>
  </main>
{% endblock %}

signup.html

{% extends 'base.html' %}
{% block title %}
  signup
{% endblock %}

{% block content %}
  <!-- create signup form here -->
  <main>
    <h2>Signup Form</h2>
    <form action="{% url 'signup' %}" method="POST">
      {% csrf_token %}
      <table id="card">
          {{ form }}
      </table>
      <button type="submit">Signup</button>
    </form>
  </main>
{% endblock %}
  • DevOps Jenkins build shell:
# Add the following command in the shell :
BUILD_ID=dontkillme
# write a command to install all the dependencies required for the django application
pip3 install --user -r requirements.txt
# write a command to migrate the application
python3 manage.py makemigrations && python3 manage.py migrate --run-syncdb
# write a command to run the django application in 0.0.0.0:8001 port in background.
# nohup python3 manage.py runserver 0.0.0.0:8001
# write a command to test the django application
python3 manage.py test
  • user_test_function.py
from django.test import Client, TestCase
from django.urls import reverse
from Play.models import User, Blog


class Test_activity(TestCase):
    def setUp(self):
        csrf_client = Client(enforce_csrf_checks=True)
        self.c = Client()

    def test_index_url(self):
        '''
        Write a code to check the index page is existing or not.
        '''
        response = self.c.get(reverse("index"))
        self.assertIn(response.status_code, [302, 200])  # redirect to login or show page

    def test_new_user(self):
        '''
        Check the user is able to signup with the following details :
        username : user01
        password : user@12345
        firstname: user01
        lastname : user
        email    : user01@leaf.com
        confirm  : user@12345
        dob      : 1999-01-01
        Write a code to check the user is able to login with the credentials :
        Username : user01
        Password : user@12345
        '''
        signup_data = {
            "username": "user01",
            "password": "user@12345",
            "confirm": "user@12345",
            "firstname": "user01",
            "lastname": "user",
            "email": "user01@leaf.com",
            "dob": "1999-01-01"
        }
        response = self.c.post(reverse("signup"), data=signup_data)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(User.objects.count(), 1)

        login_data = {'username':'user01','password':'user@12345','login':'login'}
        response = self.c.post(reverse("login"), data=login_data)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(self.c.session["user"], "user01@leaf.com")

    def test_login(self):
        '''
        Write a code to check the user is able to signup and login with the following details :
        Username  : user02
        Password  : user@12345
        firstname : user
        lastname  : 02
        email : user2@email.com
        dob : 2020-01-01
        '''
        signup_data = {
            "username": "user02",
            "password": "user@12345",
            "confirm": "user@12345",
            "firstname": "user",
            "lastname": "02",
            "email": "user2@email.com",
            "dob": "2020-01-01"
        }
        response = self.c.post(reverse("signup"), data=signup_data)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(User.objects.count(), 1)

        login_data = {'username':'user02','password':'user@12345','login':'login'}
        response = self.c.post(reverse("login"), data=login_data)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(self.c.session["user"], "user2@email.com")

    def test_create(self):
        '''
        Write a code to check signup and login with the details given for the "test_login" function.
        Then verify it is able to create blog with the Title and Content as "First blog" and "This is the first blog in this page."
        '''
        # Signup
        signup_data = {
            "username": "user02",
            "password": "user@12345",
            "confirm": "user@12345",
            "firstname": "user",
            "lastname": "02",
            "email": "user2@email.com",
            "dob": "2020-01-01"
        }
        self.c.post(reverse("signup"), data=signup_data)

        # Login
        login_data = {
            "username": "user02",
            "password": "user@12345"
        }
        self.c.post(reverse("login"), data=login_data)

        # Blog creation
        blog_data = {'title': 'First blog', 'content': 'This is the first blog in this page.', 'create_blog':'create_blog'}
        response = self.c.post(reverse("blog_create"), data=blog_data)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(Blog.objects.count(), 1)
        self.assertEqual(Blog.objects.first().title, "First blog")

Output

Blog Post Page
Blog Create Form Page
Blog Index Page
Login Form Page
Signup Form Page
Share: