Why is the file not showing up in request.files and in request.forms instead?
I'm am trying to send a file from React to flask, but when I send it, it doesn't come up in request.files where it's supposed to be, and instead in request.form. How do I fix this?
here is react code:
const data = new FormData();
data.append("file", file);
await fetch("/run", {
method: "POST",
body: data
}).then(res => res.json())
.then(data => console.log(data.file))
.catch(error => console.error(error))
}
here is the flask code:
@app.route('/run', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
if 'file' not in request.files:
flash('No file part')
return {'file': "no file part"}
file = request.files['file']
if file.filename == '':
flash('No selected file')
return {'file': 'no selected file'}
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('uploaded_file',
filename=filename))
else:
return {"file": "this a get"}
See also questions close to this topic
-
Is it possible to have an onclick() inside a functional component that executes a function of the caller in Javascript?
Hey there I'm new to Javascript and I've been looking through the forum to find an answer to my problem. I have a functional component that I call and inside of that one I want to place a button, the problem is that the function I want to call is in the file of the caller, so I always get an error. I tried multiple solutions including a function handler but it didn't work. Now I try it here, maybe someone knows something about that.
-
Return modified array after adding one element at certain position
Is there any function which inserts value at certain index and returns modified array like
filter
ormap
?I already tried
array.splice(item, 0, index)
but it returns[]
instead of modified array -
Getting an error while trying to interact with a server using socket io with node js and a react frontend
I am getting this error on the frontend.
Access to XMLHttpRequest at 'http://localhost:6969/socket.io/?EIO=4&transport=polling&t=NWJnNb2' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
The socket io documentation says that if the server is configured properly then it probably happens because the browser isnt able to reach the Socket.io server and in that case the following command:
curl "https://api.example.com/socket.io/?EIO=4&transport=polling"
is going to return something similar to this:
0{"sid":"Lbo5JLzTotvW3g2LAAAA","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":5000}
and it did.(I replaced the
https://api.examle.com
part withhttp://localhost:6969
and it returned a similar output in the console)But the documentation never explains what to do in case this actually happens and it only says "this could mean that your browser wasn’t able to reach the Socket.IO server." How do I fix it?
Here is the server code if it helps:
const express = require('express'); const app = express(); const cors = require('cors'); const socket = require('socket.io'); require('dotenv').config(); app.use(cors({ origin: '*' })); const server = app.listen(process.env.PORT, (): void => { console.log('Server listening on port ' + process.env.PORT); }); const io = socket(server); io.on('connection', (s: any) => { s.on('join', (data: any) => { console.log(data); }); s.on('disc', (data: any) => { console.log(data); }); });
And here is the frontend React code:
import React, { useState, useEffect } from 'react'; import io from 'socket.io-client'; const App = () => { // let socket; const PORT = 'http://localhost:6969/'; const [state, setState] = useState({ username: '', room: '', }); const [socket, setSocket] = useState(''); useEffect(() => { setSocket(io('http://localhost:6969', { transport: ['websocket'] })); }, [PORT]); const handleChange = (e) => { setState((prev) => { return { ...prev, [e.target.name]: e.target.value, }; }); }; const Join = (e) => { socket.emit('join', state.room); console.log(socket); }; return ( <div> <input name='username' type='text' onChange={handleChange} /> <input name='room' type='text' onChange={handleChange} /> <button onClick={Join}>Join </button> </div> ); }; export default App;
-
mobx react lite migration 'this' is undefined when callback function is called
I've migrated to react mobx lite, but although I've a solution I don't understand the error below.
I get "this is undefined", when a callback method is called via rootStore.view.openWithCallback. To fix it I have to bind the store but not sure this is supposed to be fixed like that. (On mobx-react -not lite- this was working fine)
// index.js const rootStore = new RootStore(locale) const StoreContext = React.createContext(rootStore); export const useStores = () => React.useContext(StoreContext); export const StoreProvider = ({children, rootStore}) => { return ( <StoreContext.Provider value={rootStore}>{children}</StoreContext.Provider> ); }; ReactDOM.render( <StoreProvider rootStore={rootStore}> <App /> </StoreProvider>, document.getElementById('root') ); const routes = [ { path: '/', action: () => rootStore.view.openWithCallback("/", rootStore.view.noop, true, true) }, { path: '/account', action: () => rootStore.view.openWithCallback("/account", rootStore.user.getAddresses) },...] const router = new UniversalRouter(routes) router.resolve(window.location.pathname)
rootStore.user.getAddresses is the callback. if I change it to rootStore.user.getAddresses.bind(rootStore.user) it works, but is there a more elegant way to achieve the same thing?
below more code to help understand what I could be doing wrong. thanks!
// from ViewStore (RootStore->ViewStore) @action.bound async openWithCallback(page, callback, initCat = true, awaitRequested = false) { this.loading = true this.page = page if (awaitRequested) { await this.init(initCat) } else { this.init(initCat) } await callback() // CALLBACK FOR rootStore.user.getAddresses runInAction(() => { this.loading = false }) this.ga(this.page) //google analytics } // from RootStore export default class RootStore { view user,... constructor(browserLocale) { makeAutoObservable(this) this.user = new UserStore(this) this.view = new ViewStore(this)
-
google-map-react: Map is too zoomed in at 0 zoom
I am using google-map-react to add maps to the bottom corner of my React website. However, even when I the map a
zoom
of 0, the map is pretty zoomed in.Here is a picture of what it looks like right now.
My intention is to be able to see the entire world, or at least a significant portion of it, at the lowest zoom level. On the official Google Maps website, you can see almost the entire world at once.
Is there a way to recreate this using
google-map-react
? Please let me know if you need any of the code I'm using. Thank you![Edit] Here is the CSS for the map:
.map { position: absolute; bottom: 9vh; right: 2vw; height: 33vh; width: 28%; z-index: 10; opacity: 0.9; }
-
Why only first item from list created with jQuery is sent through Ajax
I have a list that I created with jQuery as follows:
pros=[]; cons=[]; $.each($(".pro-item"), function(){ pros.push($(this).html()) }) $.each($(".con-item"), function(){ cons.push($(this).html()) })
Now I want to pass it to server for processing, so I use Ajax:
$.ajax({ data: { pros: pros, cons: cons, }, type: 'POST', dataType: "json", traditional: true, url: '/pro_con_list', success: function(data){ console.log("Ajax call successful") } })
But when server(flask/python) receives it and I print the resulting data as such:
pros = request.form.get("pros") print(pros) print(request.form.get("cons"))
It only prints the first item of the JS list that was sent. I console.log both pros and cons lists and it shows full lists:
(3) ["foo", "foo bar", "foo bar buz"] (3) ["buz", "buz bar", "buz bar foo"]
And this is what python prints it received:
foo buz
I assume I am not sending the the list properly, but the seemed to be the only way working and not printing None.
-
Getting errors on python 2 and 3 when running application
Found repository on github https://github.com/carlosperate/LightUpPi-Alarm for alarm clock which has a command line interface and web interface.
when running command line interface on python3 I receive the following error
Traceback (most recent call last): File "main.py", line 193, in <module> main(sys.argv[1:]) File "main.py", line 173, in main offset_alert_callback=alarm_offset_alert) File "/home/pi/LightUpPi-Alarm/LightUpAlarm/AlarmManager.py", line 57, in __init__ if AlarmDb().get_number_of_alarms() == 0: File "/home/pi/LightUpPi-Alarm/LightUpAlarm/AlarmDb.py", line 79, in __init__ if rows.count == 0: AttributeError: 'ResultIter' object has no attribute 'count'
When running on python2 I receive the following error
Traceback (most recent call last): File "main.py", line 193, in <module> main(sys.argv[1:]) File "main.py", line 173, in main offset_alert_callback=alarm_offset_alert) File "/home/pi/LightUpPi-Alarm/LightUpAlarm/AlarmManager.py", line 57, in __init__ if AlarmDb().get_number_of_alarms() == 0: File "/home/pi/LightUpPi-Alarm/LightUpAlarm/AlarmDb.py", line 80, in __init__ settings_table.insert(dict(snooze_time=3, offset_alert_time=-15)) File "/usr/local/lib/python2.7/dist-packages/dataset/persistence/table.py", line 66, in insert self._ensure_columns(row, types=types) File "/usr/local/lib/python2.7/dist-packages/dataset/persistence/table.py", line 198, in _ensure_columns self.create_column(column, _type) File "/usr/local/lib/python2.7/dist-packages/dataset/persistence/table.py", line 222, in create_column self.database.op.add_column( File "/usr/local/lib/python2.7/dist-packages/dataset/persistence/database.py", line 69, in op ctx = MigrationContext.configure(self.engine) File "/home/pi/.local/lib/python2.7/site-packages/alembic/runtime/migration.py", line 214, in configure "got %r" % connection, alembic.util.exc.CommandError: 'connection' argument to configure() is expected to be a sqlalchemy.engine.Connection instance, got Engine(sqlite:///alarmdatabase.db)
All dependencies installed except for dataset. Downloads to 99% then says killed on both python 2 and 3. When installed get following error
ImportError: No module named Cython.Distutils
When run on windows runs perfectly
running on raspberry pi zero w raspberry OS
Need assistance getting this working.
If you can assist on getting the server running it would be appreciated but command line first priority
Please and Thank you
-
Running Flask without internet connection, not seeing site
I want to be able to run Flask on a LAN connection without connection to the internet. When running the flask application it starts and runs on host = 0.0.0.0:5000 but the site can't be reached from browsers going to 0.0.0.0:5000. Running with an internet connection to the network allows the site to show up. When communicating from another device on the same network sending a post to the Flask's ip and correct endpoint allows for a successful http post request with response when the network does not have internet.
The main function is shown here.
if __name__ == "__main__": port = 5000 app.run(port = port,host = HOST, debug = True)
Bottomline: How do I run flask with a wifi connection that does not have internet to communicate with other devices on the network and show the site at 0.0.0.0:5000? thanks
-
Printful API fetch request returning CORS error
I am trying to retrieve data from Printful API by using a fetch get request. For some reason I am getting the following error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.printful.com/store/products/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
I've set Access-Control-Allow-Origin to the specific URL so I'm not sure why it is not allowing CORS.
fetch(printfulUrl + 'store/products/', { method: 'GET', headers: { 'Content-Type': 'application/json; charset=UTF-8', 'Access-Control-Allow-Origin': 'https://api.printful.com/store/products/', 'Authorization': 'Basic ' + APIKey }, }).then((response) => console.log(response));
I've spoken with Printful and they said that they do support JS fetch requests. They just don't have much documentation on how to make proper requests with their API.
I am currently testing locally (localhost:3000)
Cannot run a proxy because I am using authentication.
-
Why is my Printful API fetch request returning a CORS error?
I am trying to retrieve data from Prinful API by using a fetch get request. For some reason I am getting the following error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.printful.com/store/products/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
I've set Access-Control-Allow-Origin to the specific URL so I'm not sure why it is not allowing CORS.
fetch(printfulUrl + 'store/products/', { method: 'GET', headers: { 'Content-Type': 'application/json; charset=UTF-8', 'Access-Control-Allow-Origin': 'https://api.printful.com/store/products/', 'Authorization': 'Basic ' + APIKey }, }).then((response) => console.log(response));
I've spoken with Printful and they said that they do support JS fetch requests. They just don't have much documentation on how to make proper requests with their API.
I am currently testing locally (localhost:3000)
This question has not been solved.
-
will puting function inside render method slow my app
i am learning react, i am django developer and i am getting data from api and is working fine, just for a fun i wanted to update data without clicking reload, so what i did is put fetch function inside render which is looping , and it is giving real time feel, but i want to know that will doing this like this slow my app like in vannila js, since it is rendering again and again, but since react uses virtual dom i have soft side on this technique
import React from 'react'; class FetchRandomUser extends React.Component { constructor(){ super(); this.state = { data: [], }; } fetchdata(){ fetch('http://127.0.0.1:8000/api') .then(response=>response.json()) .then((data)=>{ this.setState({ data:data, }); console.log(data); }); } componentDidMount(){ this.fetchdata(); } render() { this.fetchdata(); const dat = this.state.data; const rows = dat.map((emp)=> <div> <h1>{emp.id}</h1> <h1>{emp.title}</h1> <h1>{emp.body}</h1> </div> ); return ( <div> {rows} </div> ) } } export default FetchRandomUser;