I am currently using Flask to create a website and have come across an interesting issue. There is some code that gives the user the option to input a value in for about 20 separate input fields. What I am trying to do is construct a button that would allow the user to paste in a column from an Excel table. Essentially, a button that will look at the clipboard, take the field, convert the string into an array, and place the values into each input in the order they appear in the list.
So far, I have been able to get the clipboard into a string using tk.Tk().clipboard_get(), and believe that I can get this value by making an XMLHttpRequest, but have had little luck in making it actually work.
Some code for what I am trying to accomplish:
Python:
#app.route('/some/path/here', methods = ['GET'])
def paste():
try:
values = tk.Tk().clipboard_get()
values = values.replace('\n',',')
return values
except:
return None
HTTP:
<button type="button" style="float: right" onclick="Testing()">Paste</button>
<p id="textHere"></p>
JavaScript:
<script>
function Testing() {
var wvpst = new XMLHttpRequest();
wvpst.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200) {
var list = this.responseXML;
// list = list.replace(/'/g,"").replace(/ '/g,"");
// list = list.split(", ");
document.getElementById("textHere").innerHTML = list;
}
}
wvpst.open("GET","{{ url_for('paste') }}",true);
wvpst.send();
}
</script>
For now, I am just trying to get the list of values copied from an Excel sheet, but nothing is being returned when the button is pressed. Am I simply using XMLHttpRequest incorrectly or is there something else I need to do to get this to work?
Set a debug breakpoint inside
if (this.readyState == 4 && this.status == 200) {
}
and inspect your response. Set another on the first line of your function in Flask. Those should give you visibility into where the breakdown is.
A few other, perhaps more important notes:
Point 1) In your flask try/except, on failure you should serve a response, just a 500 response. Replace return None with:
return app.make_response('Couldn't parse clipboard information!'), 500
Point 2) There is no need to pass this information to your server for processing. You can accomplish this within the javascript of the front end and save your server some processing and your client some time waiting on an HTTP response.
Have the user paste their content into a textbox or another element, and then access the value from there.
Direct clipboard access isn't something most browsers give up freely, and so best to avoid that route.
Summary:
Your xmlhttprequest looks fine to me. I would guess that your try in flask is failing and returning something useless if anything at all.
Do this in javascript.
Related
I want to use the requests.post tool to automatically query domain name attribution on this websitea website,But the return value is always empty, I guess it is because the post method failed to transfer the data to the textarea
url = 'http://icp.chinaz.com/searchs'
data = {
'hosts':'qq.com',
'btn_search':'%E6%9F%A5%E8%AF%A2', '__RequestVerificationToken=':'CfDJ8KmGV0zny1FLtrcRZkGCczG2owvCRigVmimqp33mw5t861kI7zU2VfQBri65hIwu_4VXbmtqImMmTeZzqxE7NwwvAtwWcZSMnk6UDuzP3Ymzh9YrHPJkj_cy8vSLXvUYXrFO0HnCb0pSweHIL9pkReY',
}
requests.post(url=url,data=data,headers=headers).content.decode('utf-8')
I'd be very grateful if you could point out where I'm going wrong
I have tried to replace headers and so on.
Wondering if someone can help, I'll try to explain the best I can. I am looking at a json file for various steam games. Basically what I want to do is check to see if a certain "key(?)" is present and if not then return "None".
e.g. Check to see if body[id].data.metacritic and if it does then assign score to body[id].data.metacritic.score. The same with URL. I cannot figure this out!
I have tried the following:
if(bulk.metacritic) var { score, url } = bulk.metacritic[0] || "None";
I just can't figure out how to get this right! Basically, body[id].data.metacritic doesn't exist in all json files, along with other parameters so I just want to display some placeholder text if they don't appear.
You can check if the body[id].data.metacritic is an array with a non-zero length and if so, use a value from it, otherwise use default values:
let score, url;
let data = body[id].data;
if (data && Array.isArray(data.metacritic) && data.metacritic.length > 0) {
score = data.metacritic[0].score;
url = data.metacritic[0].url;
} else {
score = url = "None";
}
console.log(score, url);
I have a spreadsheet where each row contains a SOAP request, concatenated from the data in that row. So cell G2 is a SOAP request, cell G3 is a different SOAP request, cell G4 is another SOAP request and so on. I've looked to see what is the best method for transferring those 100+ SOAP requests into SoapUI (free version) and running them all in one batch. I've not found anything that gives me the full working solution yet. Could someone suggest the best method please? Thanks in advance!
I won't tell you how to do it, but I can tell you how I did it. Concatenating XML in Excel is messy and error-prone, especialy if you have less-technical people writing the test cases. I asked for the data (parameters) in Excel.
I wrote a Groovy script that gets the data (there's a nice script that abstracts it for you), and for each test case, saved the values as properties:
new ExcelBuilder("data/MyRegressionSheetV1.2.xls").eachLine([labels:true]) { row ->
Map payLoad = [:]
if (cell(0)) {
payLoad['MyName'] = cell(0)
payLoad['MySurname'] = cell(1)
//and so on
payLoad['ExpectedResult'] = cell(12)
testRunner.testCase.testSuite.project.setPropertyValue("Name", payLoad['MyName'])
testRunner.testCase.testSuite.project.setPropertyValue("Surname", payLoad['MySurname'])
//and so on
def MyScenario = testRunner.testCase.testSuite.testCases["SOAP Request1"].run( null, true )
then made the SOAP requests with parameterised values:
<parm:Name>${#Project#Name}</parm:Name>
<parm:Surname>${#Project#Surname}</parm:Surname>
//and so on
While in the loop, you can get the response values and if you have expected results, you can compare them programmatically:
def responseSOAP = context.expand('${SOAP Request1#Response}')
def responseSection = responseSOAP =~ /requestAnswer>(.*)<\/requestAnswer/
def response = responseSection[0][1]
if (response.equals(payLoad['ExpectedResult'])) {
testResult = 'Pass'
}
}
Opensource SoapUI is very capable, and Groovy is a very cool programming language. A lot is possible once you get your head around how they work together.
EDIT:
If you want to replace the entire request, you can access it with the XmlHolder:
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
//this gets a handle on the current request XML
def oldHolder = groovyUtils.getXmlHolder( 'SOAP Request1#Request' )
//your String XML from the spreadsheet must be parsed into XML
def newHolder = new XmlSlurper().parseText(MyXMLFromSheetAsString)
//replace
context.requestContent = newHolder.xml
I have created a function in SSJS Library. Because I use it in more than one XPages.
When I call this function behind a button I cannot see the value in the field
If I print it out I can see the value at the Admin Console but cannot see it in the form Even if I get page with full refreshed.
Actually my another question is.. is it possible to compare notesXSPDocument and NotesDocument. Maybe someoen can say that what is the best way for that?
function deneme(document1:NotesXSPDocument,otherDocfromOtherDatabase:NotesDocument)
{
//do staff here
if (document1.getItemValueString("field1")==otherDocfromOtherDatabase.getItemValueString("field2"))
{ //do some staff here...
document1.replaceItemValue("fieldName","FieldValue");}
}
You can compare item values from Document and XSPDocument, just be careful with the type you are comparing.
In your code you are comparing 2 javascript strings with == operator.
The code seems to be OK, just remember to save the document1 after the changes and maybe check that the items have some value.
var valueFromXspDoc = document1.getItemValueString("field1");
var valueFromDoc = otherDocfromOtherDatabase.getItemValueString("field2");
if (valueFromXspDoc && valueFromDoc && (valueFromXspDoc === valueFromDoc)) {
// stuff here...
document1.replaceItemValue("fieldName","FieldValue");
document1.save();
}
Don not compare it with == sign. A better way is to document1.getItemValueString("field1").equals(otherDocfromOtherDatabase.getItemValueString("field2"))
I understood how we parse the url parameters in express routes, as in the example
How to get GET (query string) variables in Express.js on Node.js?
But where do the url parameters come from in the first place?
EDIT:
Apparently, I can build such a query with jquery (i.e $.get). I can append params to this query object. It s cool, but still i m trying to understand how we achieve this in the query that renders the page as a whole.
An example : when i choose the oldest tab below, how does SO add ?answertab=oldest to the url so it becomes :
https://stackoverflow.com/questions/30516497/how-do-we-add-url-parameters-ejs-node-express?answertab=oldest#tab-top
The string you're looking at is a serialization of the values of a form, or some other such method of inputing data. To get a sense of this, have a look at jQuery's built in .serialize() method.
You can construct that string manually as well, and that's pretty straight forward as well. The format is just ?var1=data1&var2=data2 etc. If you have a JSON object {"name": "Tim", "age": 22} then you could write a very simple function to serialize this object:
function serializeObject(obj) {
var str = "?";
for(var i = 0; i < Object.keys(obj).length; i++) {
key = Object.keys(obj)[i];
if (i === Object.keys(obj).length - 1)
str += encodeURIComponent(key) + "=" + encodeURIComponent(obj[key]);
else
str += encodeURIComponent(key) + "=" + encodeURIComponent(obj[key]) + "&";
}
return str;
}
Running seralizeObject({"name": "Tim", "age": 22}) will output '?name=Tim&age=22'. This could be used to generate a link or whatnot.
The page author writes them so. This is how they "come in the first place". The authors of an HTML page decide (or are told by website designers) where to take the user when he clicks on a particular anchor element on it. If they want users to GET a page with some query parameters (which their server handles), they simply add query string of their choice to the link's href attribute.
Take a look at the href attribute of the oldest tab you clicked:
<a
class="youarehere"
href="/questions/30516497/how-do-we-add-url-parameters-ejs-node-express?answertab=oldest#tab-top"
title="Answers in the order they were provided"
>
oldest
</a>
When you clicked it, the browser simply took you to path indicated in href attribute /questions/30516497/how-do-we-add-url-parameters-ejs-node-express?answertab=oldest#tab-top relative to the base URL http://stackoverflow.com. So the address bar changed.
stackoverflow.com may have its own system of generating dynamic HTML pages. Their administrators and page authors have configured their server to handle particular query parameters and have put in place their own methods to make sure that links on their pages point to the URL(including query string) they wish.
You need to provide URIs with query strings of your choice (you can build them using url.format and querystring.stringify) to your template system to render. Then make your express routes process them and generate pages depending on their value.