I have directive to display player image. I send player id to small Python script to check if image with such id exists via ajax call. If image exists, I need to return its name.
I succeeded in sending id from fronted to script and finding the image name. The problem is that I am failing to return the file name correctly. I am getting error:
HTTP Error 502.2 - Bad Gateway
The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are "HCP_23108_SmithKen.png ".
If I add headers, I am still getting error:
HTTP Error 502.2 - Bad Gateway
The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are "Content-type: text/html; charset=utf-8 HCP_23108_SmithKen.png ".
I did enabled cgi in Handler Mappings of IIS7 by following Python on IIS: how?
My question is how to perform Ajax GET request correctly without any Python frameworks? Thanks
Directives:
myDirectives.directive('headshot', function ($http) {
return {
restrict: 'AE',
scope: {
lastProID: '#lastproid'
},
template: '<img ng-src="{{proImg}}" class="headshot">',
link: function (scope, element, attrs) {
//scope.id = scope.lastProID;
attrs.$observe('lastproid', function (id) {
scope.id = id;
var src = 'img/bios/nophoto.png';
scope.proImg = (src);
var url = 'bioPhoto/bioPhoto.py';
$http.get(
url,
{
params: {'id': scope.id}
})
.success(function (data) {
var src = 'img/bios/' + data;
scope.proImg = (src);
})
.error(function (error) {
});
});
}
};
});
bioPhoto.py script:
import fnmatch
import os
rootPath = './img/bios/'
query_string=os.environ["QUERY_STRING"]
id=query_string.split("id=",1)[1]
id=id.strip()
pattern = "*" + id + "*"
print ('Content-type: text/html; charset=utf-8')
for root, dirs, files in os.walk(rootPath):
for filename in fnmatch.filter(files, pattern):
filename=filename.strip()
print(filename)
You need a blank line after your headers.
(See: http://www.oreilly.com/openbook/cgi/ch03_02.html)
Try this:
print ('Content-type: text/html; charset=utf-8\n\n')
Related
I want to upload a .wav file from react frontend to node server and then send the file to a python file for speech recognition.
I used multer to get the file in the post route. The file I get looks like this.
{
"fieldname": "file",
"originalname": "00f0204f_nohash_0.wav",
"encoding": "7bit",
"mimetype": "audio/wave",
"destination": "./public/",
"filename": "IMAGE-1635358708022.wav",
"path": "public\\IMAGE-1635358708022.wav",
"size": 32044
}
Now I want to fork a child process for python from index.js and want to sent the file for ASR.
The python file code looks like this:
import speech_recognition as sr
def read_in():
lines = sys.stdin.readlines()
return json.loads(lines[0])
def main():
a = read_in()
r = sr.Recognizer()
with sr.AudioFile(a) as source:
audio_text = r.listen(source)
try:
text = r.recognize_google(audio_text)
print('Conversion Started')
print(text)
except:
print('Error Occurred - Try Again')
How should I send the uploaded file from node to this python file for computation? I am new at this, so I am really confused.
if you are post processing the file, then get the file content with REST API:
# Postman generated
import http.client
host = "ur ip"
path = "server path:port" # port match as the express server
def webhooktriggered(path): # i haven't done any project about py web before, so goodluck
conn = http.client.HTTPSConnection(host)
payload = ''
headers = {}
conn.request("GET", path, payload, headers)
res = conn.getresponse()
data = res.read()
return (data.decode("utf-8"))
before, stream your media with express:
// Original: https://www.codegrepper.com/code-examples/javascript/node+js+express+sendfile+fs+filestream
var http = require('http'),
fileSystem = require('fs'),
path = require('path');
http.createServer(function(request, response) {
var filePath = path.join(__dirname, 'pathto/yourfilehere.wav');
var stat = fileSystem.statSync(filePath);
response.writeHead(200, {
'Content-Type': 'audio/x-wav', // change to whatever u want
'Content-Length': stat.size
});
var readStream = fileSystem.createReadStream(filePath);
// We replaced all the event handlers with a simple call to readStream.pipe()
readStream.pipe(response);
})
.listen(2000); //as soon we will use this port in rest client
Trigger when process, using axios
const axios = require('axios')
function uploadSuccess(path){ // must be the streamed express media path, so python rest can download it then
axios.get('http://pythonbackserverip/?path=' + encodeURI(path))
.then({
console.log("upload successfully!")
})
}
note: my code is not accurate, modify it before use
I am trying to send an image to flask endpoint from android application using retrofit 2 but I seem to fail every time. Flask endpoint is working with both html and postman posts so the problem is on the retrofit part.
Here is the Flask endpoint:
#app.route("/uploadfile", methods=["POST"])
def uploadsingle():
file = request.files['file']
file.save(os.path.join("/home/moralalp/mysite/", file.filename))
return "Success"
Below is the interface for retrofit:
#Multipart
#POST("uploadfile")
Call<ResponseBody> uploadPhoto(#Part("description") RequestBody description, #Part MultipartBody.Part file);
And finally, the uploadFile method:
private void uploadFile(Uri fileUri) {
final EditText name = findViewById(R.id.editText);
RequestBody descriptionPart = RequestBody.create(MultipartBody.FORM, name.getText().toString());
File originalFile = new File(getRealPathFromURI(fileUri));
RequestBody filePart = RequestBody.create(MediaType.parse(getContentResolver().getType(fileUri)), originalFile);
MultipartBody.Part file = MultipartBody.Part.createFormData("file", originalFile.getName(), filePart);
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("https://mysite.pythonanywhere.com/")
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
UserClient client = retrofit.create(UserClient.class);
Call<ResponseBody> call = client.uploadPhoto(descriptionPart, file);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Toast.makeText(MainActivity.this, "YEAH", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(MainActivity.this, "NOOO", Toast.LENGTH_SHORT).show();
}
});
}
I keep getting "NOOO" Toast message so I can not even get a response, what could be the problem here?
As for this error please use the next line to figure out what is the problem and please edit your question to contain it
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(MainActivity.this, "NOOO", Toast.LENGTH_SHORT).show();
Log.d("Error_TAG", "onFailure: Error: " + t.getMessage());
}
After that Please Filter your log cat to the Error_TAG and Add the Error in the Question
Good Luck
Ok so adding the following in the AndroidManifest.xml file solved my problem:
<manifest ... >
<!-- This attribute is "false" by default on apps targeting Android Q. -->
<application android:requestLegacyExternalStorage="true" ... >
...
</application>
</manifest>
I am trying to test a very simple Express App. I have my Express set up in a typescript file as follows to respond with the body of the request that it receives:
app.listen(3000, () => console.log('Server running on port 3000'))
app.use(bodyParser.urlencoded({
extended: true
}))
app.use(bodyParser.json())
app.get('/test', (req, res) => {
res.send(req.body)
});
I am trying to call this endpoint in a python file as follows
testUrl = 'http://localhost:3000'
path = '/test'
header = {
'Content-Type': 'application/json',
}
body = {
'artistName': 'test',
}
response = requests.request(
method="GET",
url = testUrl + path,
params=header,
data=body,
)
print(response._content)
When I run the python file, all it prints out is a set of empty brackets, telling me that the body of the request it is receiving is empty. Why is the body empty if I am setting the data parameter to a populated json object? Am I using the wrong parameters? Thanks for the help!
I don't know what you mean to do with res.send(req.body) in your Express code, but req.body is not used for a GET request in Express. That's used for a POST or PUT.
Parameters for a GET request are put in the URL as part of the queryString and will appear in the req.query object in Express.
I think your mistake is in the request,
Because you are sending your header as params
Main.js
Parse.Cloud.job("grabPrices", function(request, status) {
// Set up to modify user data
Parse.Cloud.httpRequest({
method: 'POST',
url: 'http://xxx.parseapp.com/xxx.py',
success: function(httpResponse) {
console.log(httpResponse.text);
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
}
})
});
Main.js is a Parse Cloud Job that I want to run which basically accesses a python script and runs it. Is this possible? If so, what changes do I make in my code?
I solved my problem by using Heroku.
My code is similar to #AlexCoren's answer, shown below:
Parse.Cloud.job("grabPrices", function(request, status) {
// Set up to modify user data
Parse.Cloud.httpRequest({
url: 'https://xxx.herokuapp.com/',
success: function(httpResponse) {
console.log(httpResponse.text);
status.success("Pricelist grabbed successfully!");
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
status.success("Oops.... something went wrong.");
}
})
});
And for heroku, I just slightly modified the views.py file (I just followed the tutorial 'Getting started with python', downloaded the example project and modified the \python-getting-started\hello\views.py file):
from django.shortcuts import render
from django.http import HttpResponse
import urllib2
import urllib
#import requests
import json, httplib
import time
from datetime import datetime
from .models import Greeting
# Create your views here.
def index(request):
# I put my python code here so it will run at the url `https://xxx.herokuapp.com/'
I do something similar in one of my apps. I hosted it on Heroku. The code looks as follows:
Parse.Cloud.define('MyFunction', function(request, response) {
var someParam = request.params['SOME_PARAM'];
var url = 'http://myapp.herokuapp.com/?param=' + someParam;
Parse.Cloud.httpRequest({
url: url,
success: function(httpResponse) {
console.log(httpResponse.headers);
console.log(httpResponse.text);
response.success();
}, error: function(httpResponse) {
response.error('Uh oh!');
}
});
});
That url specifies a parameter which gets sent to my server to and then used as a parameter in my python script.
Unfortunately, this is not possible. Parse backend only executes javascript files (cloud code folder) or html, css and javascript files (public folders).
Even if you are able to upload a python file to one of the folders, you want be able to execute the file.
You can upload your python file to your public folder and you would have a URL for it (mysubdomain.parseapp.com/python_file.py) but if you use Parse.Cloud.httpRequest, you'll get the content of the file, the server won't execute the file.
For example, if your python file has the following code:
print "Hello World!"
The result you'll get on your httpRequest will be:
print "Hello World!"
Instead of:
Hello World!
Which is what you want.
The python file should be hosted in other server that executes python.
I hope this makes sense.
Javier.
I am trying to post some data to a Flask server, whose code is the following:
#app.route('/tasks', methods=['POST'])
def create_task():
if not request.json or not 'title' in request.json:
abort(400)
task = {
'title': request.json['title'],
'description': request.json.get('description', ""),
}
return jsonify({'task' : task}), 201
When I run this, it works fine, and I can make POST requests successfully using curl, with the expected behavior on the back end above and the expected return value in command line. I want to make a post to this server using Swift, however, and am having trouble with that. I have followed the tutorial detailing this behavior here. In particular, I put the code in my AppDelegate.swift so it is executed as soon as the app launches. The full code is in the link posted, but for reference I am also posting it below:
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
var request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:4567/login"))
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var params = ["username":"jameson", "password":"password"] as Dictionary<String, String>
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
if(err != nil) {
println(err!.localizedDescription)
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: '\(jsonStr)'")
}
else {
// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
if let parseJSON = json {
// Okay, the parsedJSON is here, let's get the value for 'success' out of it
var success = parseJSON["success"] as? Int
println("Succes: \(success)")
}
else {
// Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: \(jsonStr)")
}
}
})
task.resume()
return true
}
However, when I launch this app, I have the following logged in my xcode
Response: <NSHTTPURLResponse: 0x7fc4dae218a0> { URL: http://localhost:5000/task } { status code: 404, headers {
"Content-Length" = 26;
"Content-Type" = "application/json";
Date = "Tue, 07 Oct 2014 19:22:57 GMT";
Server = "Werkzeug/0.9.6 Python/2.7.5";
} }
Body: {
"error": "Not found"
}
Succes: nil
I've been working with this and tinkering with the input, it seems that the back end is fine, but I'm wondering what is wrong with this front end, unfortunately Swift documentation is for the moment fairly moot on this point and seems to be the only solution floating around for RESTful API calls at the moment.
Your flask route is '/tasks' and you're trying to post to http://localhost:5000/task. Is that a typo, or are you a victim of failure to pluralize?