Get data from API and display on tempate - python

I am trying to get data from the stackoverflow API and display them on an html table in my template.
So far I have managed to get the data but cannot display them in the template. I end up getting the last one. I do know my loop is wrong, have tried a bunch of stuff but can't seem to figure it out.
My code so far:
def get_questions(request):
context = {}
r = requests.get('https://api.stackexchange.com/2.2/questions?fromdate=1525737600&order=desc&sort=activity&tagged=python&site=stackoverflow').json()
for item in r['items']:
context['owner'] = item['owner']['display_name']
context['title'] = item['title']
#some other attrs here
template = 'questions/questions_list.html'
context['greeting'] = 'Hello'
return render(request,template,context)
My template code:
I haven't done anything fancy yet. Pretty simple.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
<title>Questions</title>
</head>
<body>
{{ owner }} - {{ title }}
</body>
</html>

You need to append your result to a list and the render that list in your template.
Demo:
views.py
def get_questions(request):
context = {}
r = requests.get('https://api.stackexchange.com/2.2/questions?fromdate=1525737600&order=desc&sort=activity&tagged=python&site=stackoverflow').json()
dataList = []
for item in r['items']:
dataList.append({'owner': item['owner']['display_name'], 'title': item['title']})
#some other attrs here
template = 'questions/questions_list.html'
context['greeting'] = 'Hello'
context['data'] = dataList
return render(request,template,context)
Template
Iterate over your result and get all data
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
<title>Questions</title>
</head>
<body>
{% for i in data %}
{{ i.owner }} - {{ i.title }}
{% endfor %}
</body>
</html>

Related

how can I have a flask file wait for a specific button press in a html coded website? - python

I would like to use flask to check when a button is pressed in an HTML coded website, the website will be up and running and the py app needs to be running too and wait for the button click, then on the button click, it will get the input content and print it. How do I do this?
this is my html code:
<!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>test</title>
</head>
<body>
<input type="hallo">
<button>Hallo</button>
</body>
</html>
I have searched for a while but nothing I tried worked, please help.
some code snippets would be great, thanks.
Use a simple form that is submitted with a post request.
The value from the input field is queried using the name attribute.
The button of type submit submits the form.
from flask import (
Flask,
render_template,
request
)
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
print(request.form.get('hallo'))
return render_template('index.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>test</title>
</head>
<body>
<form method="post">
<input type="text" name="hallo" />
<button type="submit">Hallo</button>
</form>
</body>
</html>

how can I redirect to a dynamic url using HTML?

My code is
{% if user.employee.employee_id == 2 %}
<head>
<title>HTML Redirect</title>
<meta http-equiv="refresh"
content="1; url = employee/2/" />
</head>
{% elif user.employee.employee_id == 4 %}
<head> Wait!
<title>HTML Redirect</title>
<meta http-equiv="refresh"
content="1; url = employee/4/" />
</head>
As you can see from above, i am using if elif to access pages based on the id of employee and this method is not efficient. I want to change the employee_id to variable. something like this:
x = user.employee.empolyee_id
<head> Wait!
<title>HTML Redirect</title>
<meta http-equiv="refresh"
content="1; url = employee/x/" />
</head>
put the employee_id in url:
url = employee/{{user.employee.employee_id}}/

Find duplicate id attributes

Before uploading on my server I want to check if I accidentally defined an id two or more times in one of my html files:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>The HTML5 Herald</title>
<meta name="description" content="The HTML5 Herald">
<meta name="author" content="SitePoint">
<link rel="stylesheet" href="css/styles.css?v=1.0">
</head>
<body>
<div id="test"></div>
<div id="test"></div>
</body>
</html>
The idea is to print an error message if there are duplicates:
"ERROR: The id="test" is not unique."
You can do this by using find_all to gather all elements with an id attribute, and then collections.Counter to collect the ids that contain duplicates
import bs4
import collections
soup = bs4.BeautifulSoup(html)
ids = [a.attrs['id'] for a in soup.find_all(attrs={'id': True})]
ids = collections.Counter(ids)
dups = [key for key, value in ids.items() if value > 1]
for d in dups:
print('ERROR: The id="{}" is not unique.'.format(d))
>>> ERROR: The id="test" is not unique.
You could use a regex to find all ids in the HTML and then search for duplicates.
For example:
import re
html_page = """
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>$The HTML5 Herald</title>
<div id="test1"></div>
<meta name="description" content="The HTML5 Herald">
<meta name="author" content="SitePoint">
<link $rel="stylesheet" href="css/styles.css?v=1.0">
</head>
<body>
<div id="test2"></div>
<div id="test2"></div>
</body>
<div id="test3"></div>
</html>
"""
ids_match = re.findall(r'(?<=\s)id=\"\w+\"',html_page)
print(ids_match) #-> ['id="test1"', 'id="test2"', 'id="test2"', 'id="test3"']
print(len(ids_match)) #-> 4
print(len(set(ids_match))) #->3
# the following returns True if there are dupicates in ids_match
print(len(ids_match) != len(set(ids_match))) #->True

How to add className to body tag

I am trying to do something like below in plotly
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="images/favicon.ico" type="image/ico" />
</head>
<body class="nav-md">
</body>
Specifically define className for body tag and add some meta info to head tag. Could anyone please help how can I accomplish the same.
If your HTML content isn't static or if you would like to introspect or modify the templated variables, then you can override the Dash.interpolate_index method.
https://dash.plotly.com/external-resources
import dash
import dash_html_components as html
class CustomDash(dash.Dash):
def interpolate_index(self, **kwargs):
return """
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="images/favicon.ico" type="image/ico" />
</head>
<body class='nav-md'>
{app_entry}
{config}
{scripts}
{renderer}
</body>
</html>
""".format(
app_entry=kwargs["app_entry"],
config=kwargs["config"],
scripts=kwargs["scripts"],
renderer=kwargs["renderer"],
)
app = CustomDash()
app.layout = html.P("Hello World")
if __name__ == "__main__":
app.run_server(debug=True)

The current path, FirstApp/Challenge/{url 'FirstApp:Challenge1'}, didn't match any of these error

i have a challenge page to which pages challenge1 and challenge2 are linked but when i got to challenge page and try to access the challenge1 and challenge2 page i get following error
The current path, FirstApp/Challenge/{url 'FirstApp:Challenge1'}, didn't match any of these.
i have done similar things before but this one does not seem to be working ,can someone point out error and solution,please help
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Challenge</title>
</head>
<body>
<h2>There are two challenges for you.</h2>
Accept challenge1
=========================================================================<br>
Accept challenge2.
</body>
</html>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Challenge 1</title>
</head>
<body>
This is challenge 1.
<body>
</html>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Challenge 2</title>
</head>
<body>
this is challenge2.
<body>
</html>
Views.py file
def Challenge2View(request):
Challenge2Status= Challenge2.objects.filter(user=request.user)
form=Challenge1Form()
if request.method=="POST":
form=Challenge1Form(request.POST)
if form.is_valid():
form.save(commit=True)
return index(request)
else:
print("Invalid form")
return render(request,'FirstApp/Challenge2.html',{'forms':form,'Challenge2Status':Challenge2Status})
def Challenge1View(request):
Challenge1Status= Challenge1.objects.get(user=request.user)
time=request.POST.get('Time')
if time<=10:
Challenge1Status.Hours_spent_learning+=time
Challenge1Status.save()
else:
print("Time limit exceeded")
return render(request,'FirstApp/Challenge1.html',{'Challenge1Status':Challenge1Status})
def ChallengeView(request):
return render(request,'FirstApp/Challenge.html')
url.py application file
url(r'^Challenge/$',views.ChallengeView,name='Challenge'),
url(r'^Challenge1/$',views.Challenge1View,name='Challenge1'),
url(r'^Challenge2/$',views.Challenge2View,name='Challenge2'),

Categories

Resources