I'm using Flask to retrieve data from my HTML file. It seems that nothing is returned to python, and the POST does not even seem to be going through because none of the console.log statements in my JS are appearing in the console. I have followed this tutorial.
Here is my HTML/JS code:
<input id="textInput" placeholder="a tagline for an ice cream shop"></p>
document.getElementById('text-generate-button').onclick = () => {
parent.postMessage({ pluginMessage: { type: 'placeholder-frame'} }, '*')
submit_text();
function submit_text() {
var textForm = document.getElementById("textInput");
var toSend = { text: textForm.value };
console.log(toSend);
}
fetch('${window.origin}/text', {
method: "POST",
credentials: "include",
body: JSON.stringify(toSend),
cache: "no-cache",
headers: new Headers({
"accept": "application/json",
'Content-Type': 'multipart/form-data'
})
})
.then(function (response) {
if (response.status !==200){
console.log('Looks like there was a problem. Status code: ${response.status}');
return;
}
response.json().then(function (data) {
console.log(data);
});
})
.catch(function(error){
console.log("Fetch error: " + error);
});
and here is my python
######## imports ##########
from flask import Flask, jsonify, request, render_template, make_response
template_dir = '/Users/ericaluzzi/Desktop/idep/figment-MVP/'
app = Flask(__name__,template_folder=template_dir)
#############################
######## Example data, in sets of 3 ############
data = list(range(1,300,3))
print (data)
#app.route('/')
def home_page():
example_embed='This string is from python'
return render_template('ui.html', embed=example_embed)
#app.route('/text',methods=['GET','POST'])
def get_text():
req = request.get_json()
print(req)
res = make_response(jsonify({"message": "OK"}), 200)
return res
Related
I have been trying to implement the Twitch user authorization code flow. I am working on getting the authorization url generated from the django backend and pass it to my Vue front end so the user can open the user authorization page.
Postman recovers the generated url perfectly however when i try to do the same in Vue using Requests it is giving me an entirely different object.
Object { _events: {…}, _eventsCount: 1, _maxListeners: undefined, uri: {…}, method: "POST", readable: true, writable: true, explicitMethod: true, _qs: {…}, _auth: {…}, … }
auth.js:37:12
and here is what Postman returns
"{\"url\": \"https://id.twitch.tv/oauth2/authorize\", \"client_id\": \"xafkse7a6uyor8uisaet1ma36mrp9l\", \"response_type\": \"code\", \"grant_type\": \"token\", \"scope\": \"user_read\"}"
I'm not sure what could be causing this. Below is the code used to get to this point.
views.py
import json
import os
import requests
from django.http.response import JsonResponse
from rest_framework.decorators import api_view
from rest_framework import status
# get user access token
#api_view(['POST'])
def get_twitch_user_token_uri(request):
endpoint = "https://id.twitch.tv/oauth2/authorize"
token_url = {
'url': endpoint,
'client_id': settings['TWITCH_CLIENT_ID'],
'response_type': 'code',
'grant_type': 'token',
'scope': 'user_read'
}
return JsonResponse(token_url , status=status.HTTP_200_OK)
Login.vue
methods: {
login() {
const authenticating = true;
this.$store.dispatch("auth/get_twitch_user_token_uri", authenticating);
}
}
auth.js
const actions = {
get_twitch_user_token_uri({ commit, state }) {
commit(GET_TWITCH_TOKEN_URI);
console.log(this.endpoint);
return auth.twitch_token(this.endpoint)
.then(({ data }) => commit(GET_TWITCH_TOKEN, data))
.then(() => commit(GET_TWITCH_TOKEN_SUCCESS))
.catch(() => commit(GET_TWITCH_TOKEN_FAILURE));
},
}
const mutations = {
[GET_TWITCH_TOKEN_URI](state) {
const url = "http://localhost:8000/api/auth/login";
state.authenticating = true;
const r = request.post(url);
this.endpoint = r;
},
}
Above is where the error starts to occur requesting the url from my django backend. I'm sure i'm overlooking something i just don't know why it would return a the wrong response.
Any help is appreciated! Thanks.
had to do with the way i was calling the request and passing data from actions to mutations.
Login.vue
methods: {
login() {
this.$store.dispatch("auth/get_twitch_user_token_uri");
// .then(() => this.$router.push("/"));
}
}
auth.js
const actions = {
async get_twitch_user_token_uri({ commit }) {
commit(GET_TWITCH_TOKEN_URI);
const options = {
method: 'POST',
header: { 'Content-Type': 'application/json' },
};
try {
const response = await fetch("http://localhost:8000/api/auth/login", options);
const data = await response.json();
console.log(data);
commit(SET_TWITCH_TOKEN_URI, data);
return commit(GET_TWITCH_TOKEN_URI_SUCCESS);
} catch (e) {
return commit(GET_TWITCH_TOKEN_URI_FAILURE);
}
},
}
const mutations = {
[GET_TWITCH_TOKEN_URI](state) {
state.authenticating = true;
},
[SET_TWITCH_TOKEN_URI](state, data) {
state.endpoint = data;
},
}
Dears, I am new at flutter, I want to send post request from flutter to server
and this is the postman request
Image-Post-Request
Post header:
key Value
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Post Authentication:
Bear Token
Post Body:
key : Value
address : address
description: description
feedback: feedback
media: download.png
I want to make this request from flutter
This is my code:
File _img; // taken by camera
Map<String,String> headers = {
'Content-Type':'application/json',
'Authorization': 'Bearer $token',
};
final msg = jsonEncode({
"address" : _address,
"description": _description,
"feedback" : _techicalSupport,
"media" : _img;
});
try{
var response = await http.post(
"url",
headers: headers,
body: msg,
);
print("${response.toString()}");
}catch(e){
print("${e.toString()}");
}
I got this Error:
Unhandled Exception: Converting object to an encodable object failed: Instance of '_File'
Note: media is not required, when I removed it from the body it works and it create record in the database
I want to include media in the body.
How can I do it please...
This is the answer of my question, I used Dio library :
import 'package:dio/dio.dart';
File myImage;
List<File> _images = [];
// to handle image and make list of images
_handleImage()async{
File imageFile = await ImagePicker.pickImage(source: ImageSource.camera);
if(imageFile != null){
myImage = imageFile;
_images.add(imageFile);
}
}
// for post data with images
void _submit() async{
FormData formData = FormData();
_images.forEach((image) async{
formData.files.addAll(
[
MapEntry(
"media[]",
await dio.MultipartFile.fromFile(image.path),
),
]
);
});
formData.fields.add(MapEntry("address", _address),);
formData.fields.add(MapEntry("description", _description),);
formData.fields.add(MapEntry("feedback", _techicalSupport),);
var response = await new Dio().post(
postUrl,
options: Options(
headers: {
"Content-Type": "application/json",
"Authorization" : 'Bearer $token',
}
),
data: formData
);
print("${response.toString()}");
}
1.Configure FilePicker library (optional step, you may select your file using any library)
Then to pick the file
File file = await FilePicker.getFile();
2.Configure dio library , versions here
import 'package:dio/dio.dart';
then
FormData formData = FormData.fromMap({
"FIELD_NAME_WEBSERVICE_HERE": await MultipartFile.fromFile(imageFile.path,filename: "anyname_or_filename"),
"FIELD_NAME_WEBSERVICE_HERE":"sample value for another field"),
});
var response = await Dio().post("FULL_URL_HERE", data: formData);
print(response);
You need to convert _img to MultipartFile
MultipartFile file=MultipartFile.fromBytes(
'media', await filePath.readAsBytes(),
filename: 'FILE_NAME');
var request = http.MultipartRequest("POST", Uri.parse(url));
if (files != null) request.files.add(file);
You should use MultipartRequest to send file.
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:convert';
void send() async {
final msg = {
"address": "test",
"description": "test",
"feedback": "test",
};
File _img;
var image = await ImagePicker.pickImage(source: ImageSource.camera);
_img = image;
var response = await http.MultipartRequest(
'POST', Uri.parse("url"))
..fields.addAll(msg)
..files.add(http.MultipartFile.fromBytes('image', _img.readAsBytesSync(),
contentType: MediaType('image', 'jpeg'), filename: 'test.jpg'));
print(response);
}
I am facing an issue of receiving NULL response for the axios POST request I made. How do I correct this error?
I've tried to changing multipart/form-data into x-www-form-urlencoded and multipart/x-www-form-urlencoded
async submitUser() {
this.memberObj = {
id: this.memberObjLocal.id,
name: this.memberObjLocal.name,
password: this.memberObjLocal.password,
email: this.memberObjLocal.email,
password: this.memberObjLocal.password,
gender: this.memberObjLocal.gender,
experience: this.memberObjLocal.experience,
birth: this.memberObjLocal.birth,
phoneNum: this.memberObjLocal.phoneNum,
address: this.address,
introduce: this.introduce,
pic: this.pic
};
const config = {
headers: { "Content-Type": "multipart/form-data" }
};
var formData = new FormData();
for (let data in this.memberObj) {
console.log(data);
formData.append(data, this.memberObj[data]);
console.log(this.memberObj[data]);
}
for (var key of formData.entries()) {
console.log(key[0] + ", " + key[1]);
}
try {
let response = await this.$axios.$post("/users/", formData, config);
this.$router.push("/");
console.log(response) // null
} catch (e) {
console.log(e.response);
}
}
Please try to use like this
import axios from "axios";
//... your codes here
axios({
url: "/users/",
method: "post",
data: formData,
headers: config.headers
})
.then(response => {
this.$router.push("/");
console.log(response);
})
.catch(error => console.error(error));
//... and other codes here
and you can see more examples!
Here in views.py
class StockList(APIView):
#authentication_classes = (TokenAuthentication,)
permission_classes = [IsAuthenticated]
def get(self,request):
stocks = Stock.objects.all()
serializer = StockSerializer(stocks,many=True)
return Response({'user': serializer.data,'post': serializer.data})
def post(self):
pass
Here if token is not valid then it doesnt send any data..
so in react native I have to patch that error and show their invalid credentials.
So here is my react.js file
componentDidMount() {
return fetch('http://10.42.0.1:8000/stocks/',
{
method: "GET",
headers: {
'Authorization': `JWT ${"eyJhbGciOiIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InNhbSIsInVzZXJfaWQiOjYxLCJlbWFpbCI6IiIsImV4cCI6MTUwNDAxNTg4M30.o_NjgPNsxnLU6erGj5Tonap3FQFxN3Hh_SsU6IvLO9k"}`
}
})
.then((response) => response.json())
.then((responseData) => {
console.log(responseData.detail);
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.setState({
isLoading: false,
sa: ds.cloneWithRows(responseData.post),
}, function() {
});
})
.catch((error) => {
console.error(error);
});
}
here if json data is not provided then show some error..
how could I accopmlished that.
thank you.
I am using quill editor to upload an image and the an ajax function is used to send the image to views.py.
This is the python function for uploading the image.
views.py
def upload_image(request):
if request.method == 'POST':
handle_uploaded_file(request.FILES.get('file'))
return HttpResponse("Successful")
return HttpResponse("Failed")
def handle_uploaded_file(file):
with open('upload/', 'wb+' ) as destination:
for chunk in file.chunk():
destination.write(chunk)
This is the ajax request:
function upload(file, callback) {
console.log('called');
var formData = new FormData();
formData.append('file', file);
$.ajax({
url : '{% url 'dashboard:upload_image' %} ',
type : 'POST',
data : formData,
contentType: 'multipart/form-data',
headers: { "X-CSRFToken": $.cookie("csrftoken") },
processData: false,
success: function(data) {
console.log('success');
callback(data.url)
}
});
}
Function calling upload() :
function(value) {
let fileInput = this.container.querySelector('input.ql-image[type=file]');
if (fileInput == null) {
fileInput = document.createElement('input');
fileInput.setAttribute('type', 'file');
fileInput.setAttribute('accept', 'image/*');
fileInput.classList.add('ql-image');
fileInput.addEventListener('change', () => {
if (fileInput.files != null) {
upload();
}
});
this.container.appendChild(fileInput);
}
fileInput.click();
}
}
Error in string
with open('upload/', 'wb+' ) as destination:
Wrong path. Set the file name.