I'm working on an application, where user fills in form.
One of the fields asks for postcode. When request is sent, a separate thread runs python code using PYQT5, rendering page and scraping web, (don't want to pay for API from google) providing mileage between given postcode and set postcode. Results of this thread are saved in a file.
What i would like to do is to open a new webpage with information that the data is being checked. This page would run python code, which checks for results in a file (that takes up to few seconds) using while loop. if the result is in the file, the page redirect to another page.
Is there a way to render a page (or redirect to another page) without using RETURN? i understand that when I use return render_templates (page), rest of the code is ignored.
#app.route('/add_user', methods=['GET', 'POST'])
def add_user():
file = open('app/results_from_g.txt','w')
file.write('')
file.close()
form = AddForm()
if form.validate_on_submit():
url = 'https://google.co.uk/maps/dir/...'
def sendtogoogle(url):
os.system('python googlemaps_mileage.py ' +url)
thread1=threading.Thread(target=sendtogoogle, args=(url,))
thread1.start()
the next line of the code should be redirect to another page, and when results are in the file, either back here, or different page:
while result_from_file==0:
file = open('results_from_g.txt','r')
result_from_file = file.read()
if result_from_file =='': #means no data saved in the file yet
time.sleep(1)
elif wynik =='0': #means wrong postcode
//render page 'wrong postcode'
else:
//render page 'correct postcode
Related
#app.route("/admin/3")
def admin3_p():
return render_template("input_test.html")
#app.route("/admin/3", methods=['POST'])
def student_name():
with app.test_request_context('/admin/3', data='student'):
variable = request.form.get('student', list(''))
return variable
# Connect to CSV
def csv_func():
variable = student_name()
csv_f = "names.csv"
titles = ["Event", "Student", "Grade"]
students = [["Ev", "St", "Gr"], [variable]]
with open(csv_f, 'w') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow(titles)
csvwriter.writerows(students)
with open(csv_f, 'r') as csvfile:
csvreader = csv.reader(csvfile)
titles = next(csvreader)
for student in csvreader:
students.append(students)
print('Fields: ' + ', '.join(title for title in titles))
print(students)
csv_func()
I am trying to make a website with Flask. Th csv_func method is supposed to take the input from the html and print it to a csv file.
It returns "TypeError: The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a list" When it runs
Technically the error is because function with a route decorator is considered 'a view' and is supposed to return a page, yet yours student_name returns a tuple (of student names)
Yet I have to tell you that you got it wrong idea of web app syntax and structure. Your flow of control is opposite from what is should be. You should initiate model and csv changes from controller (student_name function), and you are doing it vise versa, by calling student_name from . The main code usually just start web app with something like
app.run(host='0.0.0.0', port=81)
So you should restructure you code in a so student_name function invokes csv changing function.
I guess you think that web app form is akin to input command in python, yet a web app is very different from python console input. The main difference is that website normally offer several different pages, and user is free to land on any page he likes. So normal webserver just wait for user landing to one or another page or sending one or another form. Thus the structure of web app is a set of pages, routes and controllers for that pages, and main code just starts the flask server. Go throw some introductory flask tutorial if it is still
unclear. E.g. https://flask.palletsprojects.com/en/1.1.x/quickstart/
Most web apps follow UI design pattern called Model-View-Controller, where user actions, such as opening a webpage on a specific web address or filling a form first hit some controlling code, which the initiates some changes in the model (data).
Get rid of the app.route(...) decorator above def student_name():.
I have a function calculate_full_eva_web(input:dict) it receives input dictionary several function applied on this input to create calculations dict, after calculations i want to send this data to html dashboard and after send data to html file i can play there with jinja stuff. i am unable to do so, i tried several ways but flask throws error. and also i don't know much about ajax ,may be ajax will do my work, let me know. that is why i am tagging ajax people on this post. Traceback is also attached..Thank you
In simple words, i want to send data to html in flask ! Please check my code. Let me know if i am doing anything wrong.
imports ...
from other file import other_functions
from other file import other_functions_2
from other file import other_functions_3
app = Flask(__name__, template_folder='templates/')
#app.route("/dashboard")
def calculate_full_eva_web(input:dict):
calculate_gap = other_functions(input)
calculate_matrix = other_functions_2(input)
average = other_functions_3(input)
data = dict{'calculate_gap':calculate_gap, 'calculate_matrix':calculate_matrix,'average':average}
return render_template('pages/dashboard.html', data = data)
if __name__ == "__main__":
app.run(debug=True)
The route receive a dict as input so you must change #app.route("/dashboard") to #app.route("/dashboard/<input>") and pass input to the route in the link of the route.
For example, I have a route as below.
#app.route('/user/<name>')
def user(name):
return render_template('home.html', name=name)
To pass name to the route, I access the link http://localhost:5000/user/myname.
I have problem because I can not find the reason why my function in Django views.py sometimes runs two times. When I go to url, which call function create_db in Django view, function read json files from directory, parse it and write the data in the database. Most of the time it works perfectly, but sometimes for no reason it runs two times and write the same data in the data base. Does anyone know what can be the reason why code is sometimes done twice and how can I solve the problem?
Here is my create_db function:
def create_db(request):
response_data = {}
try:
start = time.time()
files = os.listdir()
print(files)
for filename in files:
if filename.endswith('.json'):
print(filename)
with open(f'{filename.strip()}', encoding='utf-8') as f:
data = json.load(f)
for item in data["CVE_Items"]:
import_item(item)
response_data['result'] = 'Success'
response_data['message'] = 'Baza podatkov je ustvarjena.'
except KeyError:
response_data['result'] = 'Error'
response_data['message'] = 'Prislo je do napake! Podatki niso bili uvozeni!'
return HttpResponse(json.dumps(response_data), content_type='application/json')
The console output that I expect:
['nvdcve-1.0-2002.json', 'nvdcve-1.0-2003.json', 'nvdcve-1.0-2004.json', 'nvdcve-1.0-2005.json', 'nvdcve-1.0-2006.json', 'nvdcve-1.0-2007.json', 'nvdcve-1.0-2008.json', 'nvdcve-1.0-2009.json', 'nvdcve-1.0-2010.json', 'nvdcve-1.0-2011.json', 'nvdcve-1.0-2012.json', 'nvdcve-1.0-2013.json', 'nvdcve-1.0-2014.json', 'nvdcve-1.0-2015.json', 'nvdcve-1.0-2016.json', 'nvdcve-1.0-2017.json']
nvdcve-1.0-2002.json
nvdcve-1.0-2003.json
nvdcve-1.0-2004.json
nvdcve-1.0-2005.json
nvdcve-1.0-2006.json
nvdcve-1.0-2007.json
nvdcve-1.0-2008.json
nvdcve-1.0-2009.json
nvdcve-1.0-2010.json
nvdcve-1.0-2011.json
nvdcve-1.0-2012.json
nvdcve-1.0-2013.json
nvdcve-1.0-2014.json
nvdcve-1.0-2015.json
nvdcve-1.0-2016.json
nvdcve-1.0-2017.json
Console output when error happened:
['nvdcve-1.0-2002.json', 'nvdcve-1.0-2003.json', 'nvdcve-1.0-2004.json', 'nvdcve-1.0-2005.json', 'nvdcve-1.0-2006.json', 'nvdcve-1.0-2007.json', 'nvdcve-1.0-2008.json', 'nvdcve-1.0-2009.json', 'nvdcve-1.0-2010.json', 'nvdcve-1.0-2011.json', 'nvdcve-1.0-2012.json', 'nvdcve-1.0-2013.json', 'nvdcve-1.0-2014.json', 'nvdcve-1.0-2015.json', 'nvdcve-1.0-2016.json', 'nvdcve-1.0-2017.json']
nvdcve-1.0-2002.json
['nvdcve-1.0-2002.json', 'nvdcve-1.0-2003.json', 'nvdcve-1.0-2004.json', 'nvdcve-1.0-2005.json', 'nvdcve-1.0-2006.json', 'nvdcve-1.0-2007.json', 'nvdcve-1.0-2008.json', 'nvdcve-1.0-2009.json', 'nvdcve-1.0-2010.json', 'nvdcve-1.0-2011.json', 'nvdcve-1.0-2012.json', 'nvdcve-1.0-2013.json', 'nvdcve-1.0-2014.json', 'nvdcve-1.0-2015.json', 'nvdcve-1.0-2016.json', 'nvdcve-1.0-2017.json']
nvdcve-1.0-2002.json
nvdcve-1.0-2003.json
nvdcve-1.0-2003.json
nvdcve-1.0-2004.json
nvdcve-1.0-2004.json
nvdcve-1.0-2005.json
nvdcve-1.0-2005.json
nvdcve-1.0-2006.json
nvdcve-1.0-2006.json
nvdcve-1.0-2007.json
nvdcve-1.0-2007.json
nvdcve-1.0-2008.json
nvdcve-1.0-2008.json
nvdcve-1.0-2009.json
nvdcve-1.0-2009.json
nvdcve-1.0-2010.json
nvdcve-1.0-2010.json
nvdcve-1.0-2011.json
nvdcve-1.0-2011.json
nvdcve-1.0-2012.json
nvdcve-1.0-2012.json
nvdcve-1.0-2013.json
nvdcve-1.0-2013.json
nvdcve-1.0-2014.json
nvdcve-1.0-2014.json
nvdcve-1.0-2015.json
nvdcve-1.0-2015.json
nvdcve-1.0-2016.json
nvdcve-1.0-2016.json
nvdcve-1.0-2017.json
nvdcve-1.0-2017.json
The problem is not in the code which you show us. Enable logging for the HTTP requests which your application receives to make sure the browser sends you just a single request. If you see two requests, make sure they use the same session (maybe another user is clicking at the same time).
If it's from the same user, maybe you're clicking the button twice. Could be a hardware problem with the mouse. To prevent this, use JavaScript to disable the button after the first click.
I have tried to solve this problem for a week now and couldn't find a suitable solution.
I have a search bar to input gene ids (alternatively upload afile). It then queries the database and returns interactions between these genes. We display those interactions in a matrix on the html page. (I basically return a python array).
Now I want to include an export button to download the matrix / table in a csv or text file so the user can manipulate it for further research.
How can I do this without saving every query result in a file?
Because after returning the matrix, the python script (views.py) has run and the gene ids are gone.
Can it be done with jQuery?
Thank you so much for your help.
You only need to provide a link that contains current url plus a flag to indicate that it's a download csv request not a render page request:
def return_result(request):
# your original query
query = request.GET.get('id', None)
if query:
results = Model.objects.filter(field=query)
response = request.GET.get('download', None)
if response == 'csv':
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'
# create a csv
return response
else:
context = {'results': results}
return render(request, 'results.html', context)
In your page you create a link to download csv, {{ request.get_full_path }} is to get current url from request:
Download as CSV
Greetings all,
I have a python CGI script which using
print "Location: [nextfilename]"
print
After "forwarding" (the reason for the quotes there is apparent in a second), I see the HTML of the page to which it has forwarded fine, but all images, etc. are not showing. The address bar still shows the cgi script as the current location, not the HTML file itself. If I go to the HTML file directly, it displays fine.
Basically, the CGI script, which is stored in the cgi-bin, whereas the HTML files are not, is trying to render images with relational links that are broken.
How do I actually forward to the next page, not just render the next page through the cgi script?
I have gone through the script with a fine-toothed comb to make sure that i wasn't actually using a print htmlDoc command anywhere that would be interrupting and screwing this up.
Sections of Code that are Applicable:
def get_nextStepName():
"""Generates a random filename."""
nextStepBuilder = ["../htdocs/bcc/"]
fileLength = random.randrange(10)+5
for i in range(fileLength):
j = random.choice(varLists.ALPHANUM)
nextStepBuilder.append(j)
nextStepName = ""
for char in nextStepBuilder:
nextStepName += char
nextStepName += ".html"
return nextStepName
def make_step2(user, password, email, headerContent, mainContent, sideSetup, sideContent, footerContent):
"""Creates the next step of user registration and logs valid data to a pickle for later confirmation."""
nextStepName = get_nextStepName()
mainContent = "<h1>Step Two: The Nitty Gritty</h1>"
mainContent += "<p>User Name: %s </p>" % (user)
mainContent += """\
[HTML CODE GOES HERE]
"""
htmlDoc = htmlGlue.glue(headerContent, mainContent, sideSetup, sideContent, footerContent)
f = open(nextStepName, "w")
f.write(htmlDoc)
f.close()
nextStepName = nextStepName[9:] #truncates the ../htdocs part of the filename to fix a relational link issue when redirecting
gotoNext(nextStepName)
def gotoNext(filename):
nextLocation = "Location:"
nextLocation += filename
print(nextLocation)
print
Any thoughts? Thanks a ton. CGI is new to me.
You need to send a 30X Status header as well. See RFC 2616 for details.