Python :: Ajax
Чернетка! Стаття не завершена...
Get/Send json
# file: server.py
from flask import Flask, jsonify, request, render_template
app = Flask(__name__)
@app.route("/favicon.ico")
def favicon():
return "", 200
@app.route('/')
def main():
return render_template('index.html')
@app.route('/server', methods=['GET', 'POST'])
def test():
if request.method == 'GET':
message = {'a':1, 'b':0.2, 'd':'text'}
return jsonify(message)
if request.method == 'POST':
print(request.get_json())
return jsonify({'message':'OK', 'value':1000})
if __name__ == '__main__':
app.run(host='localhost', port=5000, debug=True)
# ... /templates/index.html
{{< rawhtml >}}
<html>
<body>
<button id='button'>Test</button>
<script>
const btn = document.getElementById('button');
const url = 'http://localhost:5000/server'
btn.addEventListener('click', () => {
/* -- Fetch API -- */
}, false);
</script>
</body>
</html>
{{< /rawhtml >}}
1.1. Server to Client : fetch-then-catch
fetch(url)
.then((response) => {return response.json()})
.then((data) => {
// enter you logic when the fetch is successful
console.log('data = ', data);
})
.catch((error) => {console.log(error)})
1.2. Server to Client : fetch-async-await
async function getData() {
try {
let response = await fetch(url);
let data = await response.json();
// enter you logic when the fetch is successful
console.log('data = ', data);
return data;
} catch(error) {console.log(error)}
}
getData();
2.1. Client to Server : fetch-then-catch
fetch(url,
{
method: 'POST',
headers:
{
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify( {a:7, b:0.2, str:'some string'} ),
})
.then(function (response) {return response.json()})
.then(function (data) {
// enter you logic when the fetch is successful
console.log('data = ', data);
})
.catch (function (error) {console.log(error)});
2.2. Client to Server : fetch-async-await
async function sendData() {
try {
let response = await fetch(url,
{
method: 'POST',
headers:
{
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify( {a:7, b:0.2, str:'some string'} )
});
let res = await response.json();
// enter you logic when the fetch is successful
console.log('res = ', res);
return res;
} catch(error) {console.log(error)}
}
sendData()
Upload File to Server
# ... /templates/index.html
{{< rawhtml >}}
<html>
<body>
<form method="POST" action="/upload" enctype="multipart/form-data">
<p><input type="file" name="file"></p>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
{{< /rawhtml >}}
# file: server.py
from flask import Flask, request, ..., redirect, url_for
....
@app.route('/upload', methods=['POST'])
def upload():
obj = request.files['file']
if obj.filename != '':
print(obj.read()) # read or save file
return redirect(url_for('main'))
3.2. fetch-then-catch
# ... /templates/index.html
{{< rawhtml >}}
<html>
<body>
<input id="send_file" type="file" name="file" accept ="text/*" />
<br/>
<button id='button'>Test</button>
<script>
const btn = document.getElementById('button');
const inp = document.getElementById('send_file');
const url = 'http://localhost:5000/upload'
btn.addEventListener('click', () => {
const formData = new FormData();
formData.append('file', inp.files[0]);
formData.append('value', 100);
const options = {
method: 'POST',
body: formData,
// If you add this, upload won't work (see links) !!!
// headers: { 'Content-Type': 'multipart/form-data' }
};
fetch(url, options)
.then(function (response) {return response.json()})
.then(function (data) {
// enter you logic when the fetch is successful
console.log('data = ', data);
})
.catch (function (error) {console.log(error)});
}, false);
</script>
</body>
</html>
{{< /rawhtml >}}
# file: server.py
from flask import Flask, request, ..., redirect, url_for
....
@app.route('/upload', methods=['POST'])
def upload():
# get some value
print(request.values.get("value") )
# get file
uploaded_file = request.files['file']
if uploaded_file.filename != '':
print(uploaded_file.read())
# return data
return jsonify({'save':'OK'})
Посилання