I use Flask to make a site and i want to connect to SQL.
For example in Python i wrote:
if request.method == 'POST':
if "Scelta" in request.form:
sf=request.form['Scelta']
sf1=sf.split()
sf2=int(sf1[0])
connection = sqlite3.connect('db.db')
connection.row_factory = sqlite3.Row
prod_sc=connection.execute ('SELECT * FROM "product" WHERE code=?', (sf2,)).fetchone()
connection.commit()
connection.close()
list_res = []
for row in prod_sc:
list_res.append(str(row))
lis={}
for m in prod_sc.keys():
lis[m] = prod_sc[m]
pos_lun=list(lis).index('Lun')
return render_template ('etichette/stampa.html', p_t=list_res, prod_sc=prod_sc, lis=lis, pos_lun=pos_lun)
and in the part in JS in the HTML:
var valori= {{ p_t | tojson }};
var pos_l= {{pos_lun|tojson}};
var val_dati= {{lis|tojson}};
to use the variable.
After the elaboration in the HTLM i sent whit form in Python:
<form method="POST">
<div class="row">
<input type="hidden" value="{{prod_sc.n_stampe}}" name="times_n">
<input type="hidden" value="{{prod_sc.code}}" name="scelta_num" >
<input type="hidden" id="lotto_s" name="lotto_s">
<input type="hidden" id="lotto_g" name="lotto_g">
</div>
</form>
and receive:
elif "Stampa_fin" in request.form:
ter=request.form
pr_creato = request.form.to_dict(flat=False)
temp=pr_creato['scelta_num']
scelta=''.join(temp)
temp=pr_creato['produzione']
data_pr=''.join(temp)
temp=pr_creato['scad_n']
scad_n=''.join(temp)
temp=pr_creato['scad_g']
scad_g=''.join(temp)
temp=pr_creato['lotto_s']
lotto_s=''.join(temp)
temp=pr_creato['lotto_g']
lotto_g=''.join(temp)
temp=pr_creato['stampante']
stampante=''.join(temp)
temp=pr_creato['n_copie']
n_copie=''.join(temp)
temp=pr_creato['times_n']
times_n=''.join(temp)
times_i=int(times_n)+1
connection = sqlite3.connect('db.db')
connection.row_factory = sqlite3.Row
prod=connection.execute ('UPDATE product SET data_produzione=?,old_data_produzione=?, giorni_scadenza=?,data_scadenza=?,stampante=?,lotto_s=?,lotto_g=?,n_stampe=? WHERE code=?',(data_pr,data_pr,scad_n,scad_g,stampante, lotto_s, lotto_g, times_i, scelta,))
prod_sc=connection.execute ('SELECT * FROM "product" WHERE code=?', (scelta,)).fetchone()
connection.commit()
connection.close()
is so complicated, also if i want to elaborate only in the HTML document.
There is any way to connect in JS my SQL document?
Or Php?
Thanks
i tried to use node.js, or transiction, or php
Related
I'm trying to develop a web-app with Flask and HTML and right now I need to get the user input, pass it to the Python back-end, execute a function and return its output, placing it inside an HTML element. I also want this to happen without refreshing the HTML page.
How can I do this?
Bellow I have the code that I've developed so far but it's not working correctly:
My HTML:
<div id="ThroughputRate" class="data_entry">
<form action="{{ url_for('background_check_throughputrate') }}" method="post">
<input name="throughput_rate_text" class="input_box">
<input id="checkThroughputRate" type="submit" class='new-button-data' value="Check Throughput Rate">
<output name="throughputRateResult" class="result_box" ></output>
</form>
</div>
My Flask backend:
#app.route('/background_check_throughputrate', methods=['GET', 'POST'])
def background_check_throughputrate():
if request.method == 'POST':
text = request.form['throughput_rate_text']
processed_text = str(text)
throughput = transition_throughput_rate(processed_text)
return jsonify(throughput)
My HTML (continuation to get the output of the function executed on Flask):
<script type=text/javascript>
$(function() {
$('a#checkThroughputRate').bind('click', function() {
$.getJSON('/background_check_throughputrate', function(data) {
console.log(data);
document.getElementById('throughputRateResult').innerHTML = data;
});
return false;
});
});
</script>
The idea behind my execution is that the user uses the first snippet of code (in HTML) to insert the input, this input is passed onto the second snippet of code (in flask) and finally, the output of the function is passed onto the last snippet of code (in JS inside HTML) so that it can be displayed on the corresponding HTML element.
So far, the input is being correctly processed inside flask but the issue is that when the function returns the jsonify, it appears on the screen, instead of sending it into the frontend. What am I doing wrong?
Thank you all
$.getJSON is designed to load the JSON data from endpoint using GET request, however, your Python code example responds to only POST requests.
Here is the working code:
HTML
<div id="ThroughputRate" class="data_entry">
<form action="{{ url_for('background_check_throughputrate') }}" method="post" id="throughputRateForm" enctype="multipart/form-data">
<input name="throughput_rate_text" class="input_box">
<input id="checkThroughputRate" type="submit" class='new-button-data' value="Check Throughput Rate">
<output id="throughputRateResult" class="result_box" ></output>
</form>
</div>
Python
#app.route('/background_check_throughputrate', methods=['GET', 'POST'])
def background_check_throughputrate():
if request.method == 'POST':
text = request.form['throughput_rate_text']
processed_text = str(text)
throughput = transition_throughput_rate(processed_text)
return jsonify(throughput)
JavaScript
<script type="text/javascript">
$(function () {
$('#throughputRateForm').on('submit', function (e) {
e.preventDefault();
var form = $(this)[0];
var formData = new FormData(form);
$.ajax({
url: '/background_check_throughputrate',
method: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (data) {
console.log(data);
document.getElementById('throughputRateResult').innerHTML = data;
}
});
});
});
</script>
Also, this code blindly trusts the user input and displays it on the webpage which can result to Cross-Site Scripting (XSS) and that is not good!
Avoid using innerHTML property when displaying user input, because it can be used to inject malicious HTML tags (e.g. <script>), i would highly recommend using innerText property instead.
I am making a "write anything here" webpage where users can write anything in a textbox then post it and it is visible to everyone. It worked fine till I found out that when any user writes and submits, all the others have to refresh the page so as to get the new data from database. So a solution to this was to call ajax continuously in some intervals. This would check if there are new entries in the table. If yes, then it would render it to the html without refreshing the whole page. Now I am pure ajax noob and after hours of research I am unable to find out how to do it.
Here is the html code
<div id="textArea">
<form action="http://127.0.0.1:3000" method="POST">
<br>
<textarea minlength="3" name="comment" placeholder="Enter Text Here.." required></textarea>
<input id="postButton" type="submit" name="" value="POST">
</form>
</div>
</div>
<div class="show">
{% for item in data %}
<div id="auto" class="disPost">{{item[0]}}</div>
{% endfor %}
</div>
Here the textarea is in a form and it submits the text to database via flask server.
Also, all the comments that users wrote are shown in "div.show"
Now the flask code is like this
#app.route('/', methods = ['POST', 'GET'])
def home():
if request.method == 'POST':
post = request.form["comment"]
myquery = "select p_id from posts order by p_id desc limit 1"
mycursor.execute(myquery)
new_p_id = mycursor.fetchone()[0] + 1
myquery = "select exists(select * from posts where p_des=%s)"
rec_tup = (post,)
mycursor.execute(myquery, rec_tup)
if mycursor.fetchone()[0]==0:
myquery = "insert into posts values(%s, %s)"
rec_tup = (new_p_id, post)
mycursor.execute(myquery, rec_tup)
mydb.commit()
mycursor.execute("select distinct p_des from posts order by p_id desc")
data = mycursor.fetchall()
return render_template("homepage.html", data=data)
"mydb" is the connector & "mycursor" is the connector's cursor
Now I am stuck somewhere in how to call AJAX function. I am not able to write beyond this ..
$(document).ready(function() {
setInterval(function() {
$.ajax({
url: '',
type: 'GET',
data: //something must be here,
success: function(data) {
//here "div" must be added to the "show" class - that is comment of other users
}
})
}, 3000);
});
I know that I have to do something like this but am literally not able to solve it.
I know this is not good question and I must look at tutorials first. But believe me I had it all. I am not able to solve this problem at all.
Thank you for seeing this :)
I did this on my latest project, you can try it too. But make sure to refresh only div element you want the data show, not all the page.
$(document).ready(function() {
function getData(){
$.ajax({
url: '',
type: 'GET',
data: //something must be here,
success: function(data) {
//here "div" must be added to the "show" class - that is comment of other users
}
});
}
getData();
setInterval(function() {getData()},2000);
});
I am exploring RESTful Flask API and as a learning I have created a small web form in HTML. Please see below the code for HTML.
<!DOCTYPE html>
<html>
<h2>User Input</h2>
<body
<script>
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script src="/static/js/predict.js"></script>
<p>Please enter the Power prices per unit</p>
<form method="get" action='/predict' target ="_blank"
enctype="multipart/form-data">
New Value - 1:<br>
<input type="number" id="New_val_1">
<br>
New Value - 2:<br>
<input type="number" id="New_val_2">
<br><br>
<button id="btnpredict" type="button">Predict</button>
</form>
<p>If you click the "Submit" button, the form-data will be sent to a page
called "/action_page.php".</p>
</body>
</html>'
Please see below the code for predict.js. This is a JQuery AJAX
$(function(){
$('#btnpredict').click(function(){
$.ajax({
url: '/predict',
data: JSON.stringify({userInput: uInput})
type: 'GET',
contentType: 'application/json',
success: function(response){
("#results").text(response.results);
},
error: function(error){
console.log(error);
}
});
});
});
And finally, the app.py code where the above HTML is getting rendered and upon receiving the the values passed on forms ML model is used.
from flask import Flask, redirect, request, render_template,json, Response
import statsmodels.api as sm
import numpy as np
from sklearn.externals import joblib
app = Flask(__name__)
#app.route('/')
#app.route('/home')
def home():
return render_template('index.html')
#app.route('/predict', methods = ['GET'])
def predict():
if request.method=='GET':
X_value_new_1 = request.values.get('New_val_1')
X_value_new_2 = request.values.get('New_val_2')
X_1,X_2 = X_value_new_1,X_value_new_2
testData = np.array([X_1,X_2]).astype(np.float).reshape(-1,1)
testData=sm.add_constant(testData)
pred = Regression_model.predict(testData)
dump = json.dumps({'prediction':list(pred)})
resp = Response(dump,mimetype='application/json')
return resp
return None
def load_model():
global Regression_model
Regression_model = joblib.load('E:/model_file_save')
if __name__ == "__main__":
print("**Starting Server...")
load_model()
app.run(debug=True)
Now the problem:
When I click on Predict button nothing happens. However, if on the address-bar if I write the 'http://localhost:5000/predict?New_val_1=1000&New_val_2=2000' then I get the correct prediction values in JSON format.
How to fix this issue? Is there any problem in JQuery?
Please help.
Best
AR
Read textbox values e.g. $("#tag").val() and concate with ajax url e.g.
predict?New_val_1=1000&New_val_2=2000'
and remove data property. You can also pass values using data property see below link for example.
https://www.codeproject.com/Questions/870797/How-to-pass-textbox-value-to-other-page-using-Jque
I am currently trying to learn django. I decided to create a small app. currently I am making a form to create VoteType and Voting candidates on one page. I created a page where u can add as many candidate fields as you want, but when I click the button nothing happenes and even if I don't click the button some data is saved. I was watching this django guide on youtube. This guy is making one simple form. He added method = POST and action = '' to ... and in views he used (request.POST or None). I tried to do the similar, but as my form is a bit more complicated I got really confused.
so this is my views.py code:
def create(request):
voteTypeForm = VoteTypeForm(request.POST or None)
voteForm = VoteForm(request.POST or None)
instance = voteTypeForm.save(commit=False)
instance.pub_date = timezone.now()
instance.save()
instance2 = voteForm.save(commit=False)
instance2.save()
#print instance.pub_date
context = RequestContext(request,{
'voteTypeForm': voteTypeForm,
'voteForm': voteForm,
})
return render(request, 'Vote/create.html', context)
and this is my create.html django template:
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'Vote/style.css' %}" />
<fieldset id="fieldset">
<form method = 'POST' action = ''>{%csrf_token %}
<p>{{ voteTypeForm }}</p>
</form>
<div id="placeholder">
</div>
<p>
<button type="button" name="Submit" onclick="Add();">+</button>
</p>
<input type = 'submit' value="create"/>
</fieldset>
<script type='text/javascript'>
{# document.write(code);#}
var _counter = 0;
var template = document.createTextNode('')
function appendStringAsNodes(element, html) {
var frag = document.createDocumentFragment(),
tmp = document.createElement('body'), child;
tmp.innerHTML = html;
// Append elements in a loop to a DocumentFragment, so that the browser does
// not re-render the document for each node
while (child = tmp.firstChild) {
frag.appendChild(child);
}
element.appendChild(frag); // Now, append all elements at once
frag = tmp = null;
}
function Add() {
var code = '<div id="template">' +
'<p>' +
'<fieldset id="fieldsets">' +
'<legend id="legends">Candidate No ['+ String(_counter+1) +']</legend>' +
' <form method = "POST" action = "">'+
'<input type="hidden" name="csrfmiddlewaretoken" value="{{csrf_token }}" />' +
'<p><label for="id_name">Name:</label> <input id="id_name" maxlength="50" name="name" type="text" /></p>'+
'<p><label for="id_image">Image:</label> <input id="id_image" name="image" type="file" /></p>'+
'</form>' +
' </fieldset>' +
'</p>' +
'</div>';
_counter++;
appendStringAsNodes(document.getElementById("placeholder"),code);
document.getElementById("someInput").value = _counter;
}
</script>
how do I fix this code so that my program only saves instances when I push the create button?
You still need to check that the action is a POST, and that the forms are valid, and you must redirect after a successful submission.
def create(request):
voteTypeForm = VoteTypeForm(request.POST or None)
voteForm = VoteForm(request.POST or None)
if request.method == 'POST':
# check validity separately to avoid short-cutting
vote_type_valid = voteTypeForm.is_valid()
vote_form_valid = voteForm.is_valid()
if vote_type_valid and vote_form_valid:
instance = voteTypeForm.save(commit=False)
instance.pub_date = timezone.now()
instance.save()
instance2 = voteForm.save(commit=False)
instance2.save()
return redirect('<view-you-redirect-to-on-success'>
context = RequestContext(request,{
'voteTypeForm': voteTypeForm,
'voteForm': voteForm,
})
return render(request, 'Vote/create.html', context)
The easiest way to do it is by making ajax request when you push the submit button.
Considering you have a form 'voteForm', try loading this form using django's inbuilt template as: {{voteForm.as_p}}
This will create your form for, which you have already done.
Now when you press submit button, make an ajax request with your form data in it.
The ajax request will take your data to the form and reverts back with a response which you can use to further do the processing.
A quick example for ajax request would be:
function youfunctionname()
$.ajax({
type: "POST",
url: url,
data: $("#yourformname").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data);
}
});
}
Trying to login into a sitecore site with R to fetch html tables.
Part one, login did succeed after adding the following to the code.
EVENTVALIDATION <- as.character(sub('.*id="__EVENTVALIDATION" value="([0-9a-zA-Z+/=]*).*', '\\1', html))
Using the code example from: How to login and then download a file from aspx web pages with R
Did try other possibilities but this looks most promising)
Is it just me having problems 'deciphering' the tags structure, or are there more grave errors in this approach
library(RCurl)
Set some handy curl options:
username = 'YourUser'
password = "YourPass"
url="http://formular.sinusenergi.dk/sitecore/login"
url2="http://formular.sinusenergi.dk/viewforms.aspx"
curl = getCurlHandle()
curlSetOpt(cookiejar = 'cookies.txt', followlocation = TRUE, autoreferer = TRUE, curl = curl)
##Load the page for the first time to capture VIEWSTATE:
html <- getURL(url, curl = curl)
## Extract VIEWSTATE with a regular expression or any other tool:
viewstate <- as.character(sub('.*id="__VIEWSTATE" value="([0-9a-zA-Z+/=]*).*', '\\1', html))
EVENTVALIDATION <- as.character(sub('.*id="__EVENTVALIDATION" value="([0-9a-zA-Z+/=]*).*', '\\1', html))
Set the parameters as your username, password, VIEWSTATE, EVENTVALIDATION :
params <- list(
'Login$UserName' = username,
'Login$Password' = password,
'Login$Login' = 'Login',
'__VIEWSTATE' = viewstate,
**"__EVENTVALIDATION" = EVENTVALIDATION**
)
Log in at last:
html = postForm(url, .params = params, curl = curl)
So now I do get logged in, but grepl('Logout', html) still returns false.
So now I can get to URL2 but haven't figure out how to 'trigger. the product selector, see code below.
This dos not work:
params2 <- list(
'ddlProducts' = '83d16692-63e0-4e9c-9720-0108cfd4fd05',
'__VIEWSTATE' = viewstate,
"__EVENTVALIDATION" = EVENTVALIDATION
)
##Verify if you are logged in:
html = postForm(url2, .params = params2, curl = curl)
Returns the 'product selector code, but does not trigger, the same.
Thanks
Excerpt from site code:
<!-- language: lang-html -->
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title>
</title></head>
<body>
<form method="post" action="/viewforms.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTQxMzE0MzQyMw8WAh4TVmFsaWRhdGVSZXF1ZXN0TW9kZQIBFgICAxBkZBYEAgEPZBYEAgEPEA8WBh4ORGF0YVZhbHVlRmllbGQFA0tleR4NRGF0YVRleHRGaWVsZAUFVmFsdWUeC18hRGF0YUJvdW5kZ2QQFQgMVmFsZyBwcm9kdWt0ClNQQVIgc3Ryb20WRXJodmVydiBWQVJJQUJFTCBzdHJvbQpTUE9UIHN0cm9tEkVyaHZlcnYgU1BPVCBzdHJvbQ5WQVJJQUJFTCBzdHJvbQpGQVNUIHN0cm9tEkVyaHZlcnYgRkFTVCBzdHJvbRUIAi0xJDgzZDE2NjkyLTYzZTAtNGU5Yy05NzIwLTAxMDhjZmQ0ZmQwNSRkYTdhZmNhOS1iZWVmLTQ3NDgtODhhNC0wNWQ1MTQ4NDBmZGMkYjg0ZjFiNjMtMDVkZi00MjFjLWFlNGQtMTdjYWZkY2ZmZjc0JGNhNmYxYmQwLTBlYjEtNDExOC1hYmY4LTdlZmFmYTRmNTI2YyQ2NTY2YzgyZS1mNjcyLTQwZGYtOGJkYS1hYjAzOTI3YzdiOGQkN2E3YTVmY2ItMDFkNi00Mzg1LTgwZDUtZjY4MTY5ZmI2NGJmJGY5N2FmNWI1LTAxZDYtNGU4NC1iZjUwLWZhZDU1ZTJmZDU4NxQrAwhnZ2dnZ2dnZxYBZmQCAw88KwARAQwUKwAAZAIDDw8WAh4HVmlzaWJsZWhkZBgBBQ5ndlByb2R1Y3RzRm9ybQ9nZApFHGp6DkfeGiiy/DYgq3lHp9Aq7IMgedEE3Ce3QI0m" />
</div>
<div class="aspNetHidden">
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEdAAl0n//hvd...A==" />
</div>
<div>
<div id="pForm">
<select name="ddlProducts" id="ddlProducts">
<option selected="selected" value="-1">Valg produkt</option>
<option value="83d16692-63e0-4e9c-9720-0108cfd4fd05">SPAR strom</option>
<option value="da7afca9-beef-4748-88a4-05d514840fdc">Erhverv VARIABEL strom</option>
<option value="b84f1b63-05df-421c-ae4d-17cafdcfff74">SPOT strom</option>
<option value="ca6f1bd0-0eb1-4118-abf8-7efafa4f526c">Erhverv SPOT strom</option>
<option value="6566c82e-f672-40df-8bda-ab03927c7b8d">VARIABEL strom</option>
<option value="7a7a5fcb-01d6-4385-80d5-f68169fb64bf">FAST strom</option>
<option value="f97af5b5-01d6-4e84-bf50-fad55e2fd587">Erhverv FAST strom</option>
</select>
<div>
</div>
<span id="lbResult"></span>
</div>
</div>
</form>
</body>
</html>
Solved the last part:
Needed to include: __EVENTTARGET' and the choice for the eventarget variable.
Så the final 'params' list have the following structure.
'__VIEWSTATE' = viewstate,
'__EVENTVALIDATION' = EVENTVALIDATION,
'__EVENTTARGET' = "ddlProducts",
'ddlProducts' = x[1]
Automating the admin screens of the CMS is not an easy task, and unless it is something but the very rudimentary it is likely to break in the future as content changes.
You should look into the Sitecore Item Web API instead, which will allow you to access and manipulate Sitecore conent items via a REST API returning data in JSON format. You can also apply security to restrict access and the calls can be made either from client side or from server side C# code.
Sitecore Item Web API Client Library
Content-As-A-Service and the Sitecore Item Web API
SitecoreJunkie: Sitecore Item Web API
There is also a great walkthrough by Mike Reynolds in this Youtube video.
Example usage:
var query = new SitecoreExpressionQuery(SitecoreQueryType.Read);
query.Query = "/sitecore/content/Home/*";
var credentials = new SitecoreCredentials();
credentials.UserName = "extranet\\foo";
credentials.Password = "bar";
credentials.EncryptHeaders = true;
var context = new AuthenticatedSitecoreDataContext("host", credentials);
ISitecoreWebResponse response = context.GetResponse(query);
if (response.StatusCode == HttpStatusCode.OK)
{
foreach (WebApiItem item in response.Result.Items)
{
// the Key property of the KeyValuePair holds the field id
foreach (KeyValuePair<string, WebApiField> field in item.Fields)
{
Console.WriteLine("fieldid: " + field.Key);
Console.WriteLine("fieldname: " + field.Value.Name);
Console.WriteLine("fieldtype: " + field.Value.Type);
Console.WriteLine("fieldvalue: " + field.Value.Value);
}
}
}