I was reading about Datastore exception handling here and possible errors here but I am having problems implementing it. Here's an example code of what I made.
try:
example.put()
except datastore_errors.TransactionFailedError:
self.response.write('Transaction failed, try again.')
When I try to load my page, nothing appears. I have built a little interface for interacting with my databases but that doesn't show up. If I remove the try/except statements, everything works fine.
What am I doing wrong?
Also why nothing at all is displayed? Shouldn't it display at least the HTML template and just throw an error when I try to put something in the database?
EDIT
Added handler code, more info
What I am doing here is I have a page where I choose a database. Depending on my choice, I open up a template I've made for adding easily instances to that database. So far I've made a template only for one database. I'm also using MathJax library and have check button to check the input before posting it.
When I implement the try/except statement, nothings gets rendered at all. Even the first page, which uses a completely different handler. I want to know why and also what's wrong with the try/except statement.
Hope that helps.
class MainPage(webapp2.RequestHandler):
def get(self):
page = env.get_template('main.html')
self.response.out.write(page.render())
class DatabaseHandler(webapp2.RequestHandler):
def get(self):
database = self.request.get('db')
mathPage = env.get_template('mp_database.html')
menuPage = env.get_template('mi_database.html')
if database == 'mathproblem':
self.response.write(mathPage.render())
elif database == 'menuitem':
self.response.write(menuPage.render())
def post(self):
submit = self.request.get('submit')
if submit == 'Submit':
page = env.get_template('mp_database.html')
problem = self.request.get('problem')
problem_db = MathProblem(task=problem)
problem_db.put()
value = {'added': '\(' + problem + '\)' + ' ' 'added'}
self.response.write(page.render(value))
elif submit == 'Check':
page = env.get_template('mp_database.html')
problem = self.request.get('problem')
values = {'displayed': '$$' + problem + '$$',
'problem': problem, 'text': 'Problem'}
self.response.write(page.render(values))
app = webapp2.WSGIApplication([
('/', MainPage),
('/database', DatabaseHandler),
], debug=True)
Related
I'm on a blackbox penetration training, last time i asked a question about sql injection which so far im making a progress on it i was able to retrieve the database and the column.
This time i need to find the admin login, so i used dirsearch for that, i checked each webdirectories from dirsearch and sometimes it would show the same page as index.html.
So i'm trying to fix this by automating the process with a script:
import requests
url = "http://depedqc.ph";
webdirectory_path = "C:/PentestingLabs/Dirsearch/reports/depedqc.ph/scanned_webdirectory9-3-2022.txt";
index = requests.get(url);
same = index.content
for webdirectory in open(webdirectory_path, "r").readlines():
webdirectory_split = webdirectory.split();
result = result = [i for i in webdirectory_split if i.startswith(url)];
result = ''.join(result);
print(result);
response = requests.get(result);
if response.content == same:
print("same content");
Only problem is, i get this error:
Invalid URL '': No scheme supplied. Perhaps you meant http://?
Even though the printed result is: http://depedqc.ph/html
What am i doing wrong here? i appreciate a feedback
This question already has answers here:
Are global variables thread-safe in Flask? How do I share data between requests?
(4 answers)
Closed 1 year ago.
App works perfectly locally but crushes after deployment- seems like it does so when I get to points where operations on variables take place.
I've looked up other similar questions but with no luck.
I assume I am making some fundamental mistake however I am not able to identify it. I was thinking perhaps something with Flask app session settings and the way requests are handled.
It's my first independent project and I realize that there must be more pythonic way of achieving things however I was just focusing on problem solving with this one.
After deployment app either crushes (NoneType object) or goes into the loop looking like variables are not being set at all- none of which happens when app is tested locally.
Fragment of code (up to the point where app crushes- I don't want to spam entire code here):
from flask import Flask, render_template, request, flash, redirect, url_for
import codecs
import datetime
from sq_search import *
from list_creator import list_creator
app = Flask(__name__)
app.secret_key= 'dev'
# Global variables created- to avoid "not defined error" in certain parts of script-
# depending on user choice
stype=None
namesearch=None
final_name=None
results=None
ticker_result=None
name_result=None
company=None
from_date=None
to_date=None
disable_1st=None
email_name=None
#app.route('/')
def home():
# Setting global variables used in search to None- in case user stops search, goes to
# other page and returns back to search- avoids errors
global stype, namesearch, final_name, results, ticker_result, name_result, company
stype=None
namesearch=None
final_name=None
results=None
ticker_result=None
name_result=None
company=None
return render_template("home.html")
#app.route('/seng/', methods=['POST','GET'])
def seng():
global stype, namesearch, final_name, results, ticker_result, name_result
search_options_title="Chosen search options:"
# Using 'try except' block to avoid errors- in case user presses go back or refreshes the
# page the script will execute further and eventuall assign variables to None letting
# the user start new search rather than returning error
if stype == None:
try:
if request.method=="POST":
global search_options
stype=request.form["stype"]
if stype == 'name':
search_options=[">Chosing by Name"]
return render_template("seng.html", pic1="pic1.html", search_options=search_options_title+"<br><br>", search_by=search_options[0],
choice2="choice2.html")
if stype == 'ticker':
search_options=[">Chosing by ticker"]
return render_template("seng.html", pic1="pic1.html", search_options=search_options_title+"<br><br>", search_by=search_options[0],
choice2="choice2tick.html")
except:
pass
if namesearch==None and stype=='ticker':
try:
if request.method=="POST":
ticker_search=request.form["tickersearch"].upper()
get_ticker(ticker_search)
if ticker_result:
stype=None
return redirect(url_for('final_stage'))
else:
ticker_search=None
notick_error="<p style='font-size: 1.4vw;color: red'>Ticker incorrect! Inster S&P 500 ticker, search again by name or browse all companies from main menu</p>"
return render_template("seng.html", pic1="pic1.html", search_options=search_options_title+"<br><br>", search_by=search_options[0],
choice2="choice2tick.html", notick_error=notick_error)
except:
stype=None
pass
elif namesearch==None and stype=='name':
if len(search_options) > 1: # Delets previously used search from right side menu if there was one already
del search_options[1]
if request.method=="POST":
try:
namesearch=request.form["namesearch"]
if namesearch != None:
get_names(namesearch)
if results:
list_creator(results) # Creates HTML script with drop down list of all matches
search_options.append(namesearch)
number_of_options=f"<br><p style='font-size: 1.3vw'>Number of matching results: {len(results)}</p>"
results=None
namesearch=None
return render_template("seng.html",pic1="pic1.html", pic2="pic2.html", search_options=search_options_title+"<br><br>",
search_by=search_options[0]+"<br><br>", search_name=">Look for: '"+search_options[1]+"'<br>",
number_of_options=number_of_options, choice3="choice3.html")
else:
noname_error= "<br><p style='font-size: 1.4vw;color: red'>No matches- no such company in S&P 500. Broaden the search or browse all companies in main menu</p>"
results=None
namesearch=None
return render_template("seng.html", pic1="pic1.html", search_options=search_options_title+"<br><br>", search_by=search_options[0],
choice2="choice2.html", noname_error=noname_error)
except:
stype=None
namesearch=None
results=None # Setting all variables to None- in case user went back a page during search-
ticker_result=None # otherwise would return an error
final_name=None
name_result=None
if final_name==None:
try:
if request.method=="POST":
final_name=request.form["name_final"]
name_result=get_all_byname(final_name) # Function retrives full data based on final user choice from drop down list
return redirect(url_for('final_stage'))
except:
pass
else:
namesearch=None # Same reason as previously- avoiding errors
stype=None
final_name=None
results=None
ticker_result=None
name_result=None
return render_template("seng.html", choice1="choice1.html")
The interpreter is confused about choosing definition for variable. Why do you keep global in function? Anything outside function is global. In case of switching contexts, you could use Flask session or Flask g.
Official Documentation
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 copied and pasted code into my IDE (TextWrangler). Now when I try to run my code, I get a ton of random errors regarding indentation and invalid syntax.
The code worked perfectly before I copied & pasted it from one Django view into another. I'm almost 100% sure the code is still correct in my new view, however, every time it runs I'll get a ton of errors relating to indentation and invalid syntax (even multiline comments like ''' trigger an "invalid syntax on line 234" error.
I've tried switching IDE's over to sublime, and even backspacing all indentations and then retabbing them to no avail. Each time I fix an "error" on one line, a new error on another line is created.
My code is below, please let me know any thoughts on how to fix.
#require_POST
def pay(request):
if request.method == 'POST':
form = CustomerForm(request.POST)
if form.is_valid():
# If the form has been submitted...
# All validation rules pass
#get the customer by session'd customer_id
c = get_object_or_404(Customer, pk = request.session['customer_id'])
#assign shipping info from POST to the customer object
c.first_name = request.POST['first_name']
c.last_name = request.POST['last_name']
c.street_address = request.POST['street_address']
c.city = request.POST['city']
c.state = request.POST['state']
c.zip = request.POST['zip']
#assign email info from POST to the customer object
c.email_address = request.POST['email_address']
stripe.api_key = REDACTED
# Get the credit card details submitted by the form
token = request.POST['stripeToken']
#tries to save the newly added form data.
try:
#save the new customer object's data
c.save()
########## THIS HANDLES CREATING A NEW STRIPE PAYMENT ################
# Create a Customer
try:
customer = stripe.Customer.create(
card=token,
plan="monthly",
email= c.email_address)
#need to save customer's id (ex: c.stripe_id = token.id)
#if there's a token error
except stripe.error.InvalidRequestError, e:
pass
#if the card is declined by Stripe
except stripe.error.CardError, e:
body = e.json_body
err = body['error']
print "Status is: %s" % e.http_status
print "Type is: %s" % err['type']
print "Code is: %s" % err['code']
# param is '' in this case
print "Param is: %s" % err['param']
print "Message is: %s" % err['message']
except stripe.error.AuthenticationError, e:
# Authentication with Stripe's API failed
# (maybe you changed API keys recently)
pass
except stripe.error.APIConnectionError, e:
# Network communication with Stripe failed
pass
except stripe.error.StripeError, e:
# Display a very generic error to the user, and maybe send
# yourself an email
pass
except Exception, e:
# Something else happened, completely unrelated to Stripe
pass
return render(request, 'shipment/confirm.html', {'date' : 'April 15, 2014'})
#passes the context to the template for confirming the customer's data
#context = { 'email_address' : c.email_address, 'first_name' : c.first_name,
# 'last_name' : c.last_name, 'street_address' : c.street_address,
# 'city' : c.city, 'state' : c.state, 'zip' : c.zip, }
#return render(request, 'shipment/pay.html', context)
#If there is a duplicate email it redirects the user back to the form with no error message.
#If anything else happens, it redirects the user back to the form.
else:
form = CustomerForm() # An unbound form
return render(request, 'shipment/createAccount.html', { 'form': form } )
Here's a couple of screenshots of your code in my editor with tabs (set to 4) and space characters shown in a reddish color. As you can see it contains quite a hodgepodge of the two on many lines. Python is very whitespace sensitive and it's important to be consistent. This is usually handled by configuring your editor to always convert tabs to n whitespace characters (or vice versa, but the former is often preferred).
To fix your problem, re-indent everything using a single method. My editor also has a convert-tabs-to-spaces command which could be used first to simplify the task somewhat.
This is why you should use soft tabs instead of hard tabs. You have at least one line that mixes them (check out the line with c.save()), looking at the edit version of your code. Change your IDE settings to always use spaces or tabs (if you haven't already), I recommend spaces.
See this question for how to view whitespace in sublime to find the offending tab character.
So, I'm trying to make a simple call using jQuery .getJSON to my local web server using python/django to serve up its requests. The address being used is:
http://localhost:8000/api/0.1/tonight-mobile.json?callback=jsonp1290277462296
I'm trying to write a simple web view that can access this url and return a JSON packet as the result (worried about actual element values/layout later).
Here's my simple attempt at just alerting/returning the data:
$.getJSON("http://localhost:8000/api/0.1/tonight-mobile.json&callback=?",
function(json){
alert(json);
<!--$.each(json.items, function(i,item){
});-->
});
I am able to access this URL directly, either at http://localhost:8000/api/0.1/tonight-mobile.json or http://localhost:8000/api/0.1/tonight-mobile.json&callback=jsonp1290277462296 and get back a valid JSON packet... So I'm assuming it's in my noob javascript:)
My views.py function that is generating this response looks as follows:
def tonight_mobile(request):
callback = request.GET.get('callback=?', '')
def with_rank(rank, place):
return (rank > 0)
place_data = dict(
Places = [make_mobile_place_dict(request, p) for p in Place.objects.all()]
)
xml_bytes = json.dumps(place_data)
xml_bytes = callback + '(' + xml_bytes + ');'
return HttpResponse(xml_bytes, mimetype="application/json")
With corresponding urls.py configuration:
(r'^tonight-mobile.json','iphone_api.views.tonight_mobile'),
I am still somewhat confused on how to use callbacks, so maybe that is where my issue lies. Note I am able to call directly a 'blah.json' file that is giving me a response, but not through a wired URL. Could someone assist me with some direction?
First, callback = request.GET.get('callback=?', '') won't get you the value of callback.
callback = request.GET.get( 'callback', None )
Works much better.
To debug this kind of thing. You might want to include print statements in your Django view function so you can see what's going on. For example: print repr(request.GET) is a helpful thing to put in a view function so that you can see the GET dictionary.