Не получается отправить JSON из Java на Flask сервер

Я хочу отправить запрос на сервер сделанный на Flask запрос с данными в формате JSON(в некоторых случаях POST запрос, а в некоторых случаях GET) из программы написанной на Java. Я столкнулся со следующей проблемой, при отправке данных сервер выдает ошибку 500:

Traceback (most recent call last):   File "E:\Programms\Anaconda\lib\site-packages\flask\app.py", line 2292, in wsgi_app     response = self.full_dispatch_request()   File "E:\Programms\Anaconda\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request     rv = self.handle_user_exception(e)   File "E:\Programms\Anaconda\lib\site-packages\flask\app.py", line 1718, in handle_user_exception     reraise(exc_type, exc_value, tb)   File "E:\Programms\Anaconda\lib\site-packages\flask\_compat.py", line 35, in reraise     raise value   File "E:\Programms\Anaconda\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request     rv = self.dispatch_request()   File "E:\Programms\Anaconda\lib\site-packages\flask\app.py", line 1799, in dispatch_request     return self.view_functions[rule.endpoint](**req.view_args)   File "server.py", line 42, in change_user     user_dict = json.loads(request.json)   File "E:\Programms\Anaconda\lib\json\__init__.py", line 341, in loads     raise TypeError(f'the JSON object must be str, bytes or bytearray, ' TypeError: the JSON object must be str, bytes or bytearray, not dict 

При этом Flask сервер выглядит вот так:

import numpy as np import pandas as pd from os.path import isfile from datetime import datetime import sys from flask import Flask, request import json  app = Flask(__name__)  @app.route('/try_server', methods=['POST']) def try_server():     user_dict = json.loads(request.json)     return 'OK'  app.run(host='', port=666) 

А запрос я осуществляю с помощью следующего кода написанного на Java:

import org.json.JSONObject;  import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder;  public class SendTest2001 {     public static void main(String[] args) throws UnsupportedEncodingException {         URL url;         HttpURLConnection connection = null;         String targetURL = "http://c7c8a0a3.ngrok.io/change_user";          try {             //Create connection             url = new URL(targetURL);             JSONObject jo = new JSONObject();             jo.put("id", "148866618");             jo.put("ves", "1e44");             jo.put("rost", "1.77");             jo.put("dr", "2018.09.20 23:15:19");             connection = (HttpURLConnection) url.openConnection();             connection.setRequestMethod("POST");             connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");             //connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");              connection.setRequestProperty("Content-Length", "" +                     Integer.toString(jo.toString().getBytes("UTF-8").length));             //       connection.setRequestProperty("Content-Language", "en-US");              connection.setUseCaches(false);             connection.setDoInput(true);             connection.setDoOutput(true);              //Send request             DataOutputStream wr = new DataOutputStream(                     connection.getOutputStream());             wr.writeBytes(jo.toString());             wr.flush();             wr.close();              //Get Response             InputStream is = connection.getInputStream();             BufferedReader rd = new BufferedReader(new InputStreamReader(is));             String line;             StringBuffer response = new StringBuffer();             while ((line = rd.readLine()) != null) {                 response.append(line);                 response.append('\r');             }             System.out.println("Успех!");             rd.close();         } catch (Exception e) {              e.printStackTrace();             System.out.println("Ошибка");          } finally {              if (connection != null) {                 connection.disconnect();             }         }     } } 

Flask app to administrate network interfaces

I made a Flask app that consists of 3 pages.

  • Index: Indexes to the 2 pages
  • SubnetOverview: SSH’s into the server and executes ifconfig, then returns the output to a webpage.
  • AddSubnet: Has a HTML form where the administrator can fill in the desired VLAN id and subnet. This gets added to the netplan file and netplan apply gets executed to apply the changes.

     #Flask app that interacts with a router running on a virtual machine, enbales administrator to list current network interfaces and make a new subinterface via SSH.

from flask import Flask, render_template, request, redirect import paramiko import ssl app = Flask(__name__) context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) context.load_cert_chain('certificates/cert.pem', 'certificates/key.pem') SERVER_IP = "" SERVER_USERNAME = "root" SERVER_PASSWORD = "secret123" SERVER_PORT = 22 SERVER_IFCONFIG = "/sbin/ifconfig" @app.route('/') def index(): return render_template('index.html') @app.route('/SubnetOverview') def SubnetOverview(): #Try to SSH into the server and execute the command client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(SERVER_IP, port=SERVER_PORT, username=SERVER_USERNAME, password=SERVER_PASSWORD) stdin, stdout, stderr = client.exec_command(SERVER_IFCONFIG, get_pty=True) output = stdout.readlines() output = ''.join(output) output = output.replace("\r\n", "<br />") client.close() return render_template('SubnetOverview.html', ssh_output=output) @app.route('/AddSubnet', methods = ['POST', 'GET']) def AddSubnet(): if request.method == 'POST': #Getting the data from the HTML form formdata = request.form.to_dict() vlanid = formdata.get('vlanid') address = formdata.get('address') command = " vlan" + vlanid + ":\n id: " + vlanid + "\n link: eth0\n addresses: [ \"" + address + "\" ]\n" #Opening an SFTP connection transport = paramiko.Transport((SERVER_IP, SERVER_PORT)) transport.connect(username=SERVER_USERNAME, password=SERVER_PASSWORD) sftp = paramiko.SFTPClient.from_transport(transport) file=sftp.file('/etc/netplan/01-network-manager-all.yaml', "a", -1) file.write(command) file.flush() SERVER_COMMAND = "sudo netplan apply" sftp.close() transport.close() #Opening SSH connection to send a command that apply's the config client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(SERVER_IP, port=SERVER_PORT, username=SERVER_USERNAME, password=SERVER_PASSWORD) stdin, stdout, stderr = client.exec_command(SERVER_COMMAND, get_pty=True) client.close() return redirect("/SubnetOverview") return render_template('AddSubnet.html') if __name__ == "__main__": app.run(host='', port=443, ssl_context=context)

Ошибка 500 , как только запускается локальный сервер Flask

Код :

from flask import Flask app = Flask(__name__)  @app.route('/')  def hello() -> str:     return print('Python Flask Framework')   app.run() 

То , как это выглядит в браузере : Ошибка на веб-странице

То , что выводит консоль после запуска программы :


Why does Jobal’s trusted consort Aazon introduce the party to River Mist and Flask of Wine?

I’ve never understood this, and it seems so logically inconsistent that I’m inclined to believe this is a typo Wizards’ part.

To give some background to this question, Jobal is one of the Merchant Princes who deals specifically with guides. All guides who work ‘legally’ in Port Nyanzaru pay a fee to Jobal. If the situation comes up, Aazon, Jobal’s “trusted spy, confidante, and consort” will take the party and introduce them to specific guides around the city.

If the characters follow Jobal’s advice and accompany Aazon, give them copies of handouts 2, 3, 4, 5, 6, and 8 (see appendix E) as Aazon introduces the party to various guides in the city.

However, handout 8 introduces the characters to River Mist and Flask of Wine, unregistered guides who have this to say in their handout:

! Beware Jobal and his no-good flunkies! That merchant prince is as trustworthy as a sack of snakes, as are most of his “guides.” If you choose us, we will never lead you astray. “River and Flask are up to the task!” That’s our motto! Chult is our playground. We’re fast, reliable, and know what we’re doing. Five gold pieces per day and a 30-day advance is what Jobal’s flunkies demand. We’re happy to serve as guides for only 4 gold pieces a day with no payment up front. Even better, we’ll waive the fee entirely for equal shares of whatever treasures we help find.

This introduction makes no sense for a variety of reasons:

1) River Mist and Flask of Wine are unregistered guides. Unregistered guides are “…beaten, blinded, or beheaded.” by Jobal.

2) River Mist and Flask of Wine have no respect for Jobal. This reinforces point 1.

3) River Mist and Flask of Wine are shady, and will only meet in the seedier areas of the map like Malar’s Throat or the warehouses at night, mainly because they are afraid of Jobal’s punishment.

4) Aazon’s loyalty to Jobal is “beyond reproach”. It makes no sense for him to introduce the party to guides this disrespectful.

With the above observations, I’m inclined to believe that there was some sort of printing error, and Salida (handout 9) was supposed to be introduced in place of River Mist and Flask of Wine, which makes much more sense.

Are there any lore reasons why Aazon would introduce the party to these two guides? Are there any clarifications on the part of Wizards’ that perhaps elaborate on this logical incongruity?

Cross-Origin Request Blocked with Flask when using BasicAuth

I have a Flask application containing various images displaying some clusters constructed by a K-Means algorithm. The user should be able to select one or several images and afterwards get redirected to a web-page where the clusters can be further assessed. The application worked as intended until I added basic access authentication.

Specifically, my (simplified) python script goes as follows:

from flask import Flask, render_template, request, redirect, url_for  from flask_cors import CORS from flask_basicauth import BasicAuth  app=Flask(__name__)  app.config['BASIC_AUTH_USERNAME'] = os.environ['AUTH_USERNAME'] app.config['BASIC_AUTH_PASSWORD'] = os.environ['AUTH_PASSWORD'] app.config['BASIC_AUTH_FORCE']= True basic_auth=BasicAuth(app)  CORS(app)   @app.route('/') def show_index():     images=os.listdir(app.root_path+"/static/img/")     return render_template("cluster_images.html", cluster_images = images)  @app.route("/filter", methods=["POST", "GET"]) def filter(): if request.method=="POST":     sel=request.get_json()  #Do some operations with sel 

The problem appears when I try to redirect to the /filter route from the main route which is done by “btn1”. The following shows the function from “cluster_images.html” taking care the http request when btn1 is fired

$  ("document").ready(function() {     $  ("#btn1").click(function(){ $  .ajax({     type: 'POST',     beforeSend: function(){         $  ('.loader')},         contentType: 'application/json',         url:  "http://localhost:5000/filter",         dataType : 'html',         data : JSON.stringify(images), success: function(){window.location.href = "http://localhost:5000/filter"} }) }) }) 

When I press the button I get the following error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/filter. (Reason: CORS preflight channel did not succeed).[Learn More]

Flask API endpoints for users and reports

I made a FLASK project with API endpoints. I’m using flask-restful, flask-jwt-extended and postgresql.

enter image description here

You can see the full code on my github repo

The README has further instructions.

For now, as a sample, I’ll post the code relevant to that handles the database connection:


import os import psycopg2 from flask import current_app from werkzeug.security import generate_password_hash   class DBModel:      def __init__(self):          with current_app.app_context():              self.connect = psycopg2.connect(current_app.config['DB_URL'])          self.cursor = self.connect.cursor()       def create_tables(self):          queries = [              """CREATE TABLE IF NOT EXISTS users (                  id serial NOT NULL UNIQUE,                  isadmin boolean NOT NULL,                  firstname varchar(255) NOT NULL,                  lastname varchar(255) NOT NULL,                  email text NOT NULL UNIQUE,                  phonenumber text NOT NULL UNIQUE,                  username varchar(255) NOT NULL PRIMARY KEY UNIQUE,                  password text NOT NULL,                  registered timestamp with time zone DEFAULT (now())              )""",              """CREATE TABLE IF NOT EXISTS reports (                  id serial NOT NULL PRIMARY KEY UNIQUE,                  reporter varchar(255) NOT NULL,                  type text NOT NULL,                  location text NOT NULL,                  comment text NOT NULL,                  status text NOT NULL,                  created timestamp with time zone DEFAULT (now()),                  FOREIGN KEY(reporter) REFERENCES users(username)              )"""          ]          for query in queries:              self.cursor.execute(query)              self.connect.commit()       def clear_database(self):          tables = ["users", "reports"]          for table in tables:              self.cursor.execute(                  "DROP TABLE IF EXISTS {} cascade;".format(                      table                  )              )              self.connect.commit()       def create_user(self, new_user):          self.cursor.execute("""              INSERT INTO users (                  isadmin, firstname, lastname, email,                  phonenumber, username, password              ) VALUES(%s, %s, %s, %s, %s, %s, %s) RETURNING username;""", (                  new_user['isadmin'], new_user['firstname'],                  new_user['lastname'], new_user['email'],                  new_user['phonenumber'], new_user['username'],                  new_user['password']              )          )          self.connect.commit()       def get_specific_from_table(self, table, table_key, table_value):          self.cursor.execute(              "SELECT * FROM {} WHERE {}='{}'".format(                  table, table_key, table_value              )          )       def check_admin_existence(self):          self.cursor.execute("SELECT * FROM users WHERE username='liukang';")          return self.cursor.fetchone()       def create_admin(self):          admin = self.check_admin_existence()          if not admin:              new_admin = {                  "isadmin": True,                  "firstname": "Liu",                  "lastname": "Kang",                  "email": "liukang@gmail.com",                  "phonenumber": "+2542345678901",                  "username": "liukang",                  "password": generate_password_hash("liukang")              }           self.create_user(new_admin) 

Python Flask website

I’m new to programming and in back-end. Right now I’m trying to learn flask, so I wrote a very simple website that currently encrypts and decrypts the message using RSA and DES.

I feel like my app.py file is just bad and should do it much better. I mean, there’re a lot of repeating code like this:

@app.route('/rsa_encrypt', methods=['GET', 'POST']) def RSA_enc():     global get_form     if request.method == "GET":         get_form = True         return render_template('rsa_encrypt.html', gf=get_form)     else:         get_form = False         rsa = RSA(request.form.get('pt'), p=request.form.get('p'),                   q=request.form.get('q'), e=request.form.get('e'))         return render_template('rsa_encrypt.html', gf=get_form, rsa=rsa, gspn=gspn) 

I tried to write some decorators for those routes, but they didn’t work well.

Can you take a look and tell me what should I do better? It works but I think not as well as it should.


from flask import Flask, render_template, request, url_for, jsonify from ciphers import RSA, DES from prime import generate_semiprime_number as gspn  app = Flask(__name__) get_form = None  @app.route('/') def index():     return render_template('index.html')  @app.route('/rsa_encrypt', methods=['GET', 'POST']) def RSA_enc():     global get_form     if request.method == "GET":         get_form = True         return render_template('rsa_encrypt.html', gf=get_form)     else:         get_form = False         rsa = RSA(request.form.get('pt'), p=request.form.get('p'),                   q=request.form.get('q'), e=request.form.get('e'))         return render_template('rsa_encrypt.html', gf=get_form, rsa=rsa, gspn=gspn)  @app.route('/rsa_decrypt', methods=['GET', 'POST']) def RSA_dec():     global get_form     if request.method == "GET":         get_form = True         return render_template('rsa_decrypt.html', gf=get_form)     else:         get_form = False         ct = [int(x) for x in request.form.get('ct')[1:-1].split(',')]         rsa = RSA(ciphertext=ct, p=request.form.get('p'),                   q=request.form.get('q'), e=request.form.get('e'))         return render_template('rsa_decrypt.html', gf=get_form, rsa=rsa)  @app.route('/des_encrypt', methods=['GET', 'POST']) def DES_enc():     global get_form     if request.method == "GET":         get_form = True         return render_template('des_encrypt.html', gf=get_form)     else:         get_form = False         des = DES(request.form.get('pt'), user_key=request.form.get('key'))         return render_template('des_encrypt.html', gf=get_form, des=des)  @app.route('/des_decrypt', methods=['GET', 'POST']) def DES_dec():     global get_form     if request.method == "GET":         get_form = True         return render_template('des_decrypt.html', gf=get_form)     else:         get_form = False         des = DES(ciphertext=request.form.get('ct'), user_key=request.form.get('key'))         return render_template('des_decrypt.html', gf=get_form, des=des)  @app.route('/gpsn', methods=['POST']) def _gpsn():     return jsonify({'result' : str(gspn(request.form['bits']))})   if __name__ == '__main__':     app.run() 

Other files repository. It’s also hosted so you can quickly take a look.

Securing Flask admin pages

We’ve been developing a Flask app for a customer and a part of the agreement was that “customer admins” would be allowed to access Flask admin page to manage users, roles and business entities.

The admin functionality is based on flask-admin package and we are using flask-jwt-extended keeping the access token in the cookies. The passwords are pbkdf2:sha256-hashed with a salt; neither passwords, nor password hashes are ever shown in the admin. Everything is HTTPS.

One other thing we did was moving from the default admin/ to a custom endpoint name.

What else could we do to make the Flask admin page more secure?

Please let me know if any other details are needed.

Page view in MongoDB and Flask

I want to be able to increment the value of a view key through flask everytime a page is refreshed. My mongo key/value is as follows:

"views": 0 

flask framework and my route looks like this:

@app.route('/get_breakfast') def get_breakfast():     return render_template("breakfast.html",     recipes = mongo.db.recipes.find()) 

Is it possible to increment the key


<strong>Views</strong> {{ recipe.views }} 

Installing elasticsearch-HQ I have cannot import name ‘Flask’ error

Under kubuntu 18 I try to install elasticsearch-HQ,as written here http://docs.elastichq.org/installation.html#installation

But I got error :

pip install -r requirements.txt ... Successfully built alembic Installing collected packages: jmespath, itsdangerous, MarkupSafe, Jinja2, Werkzeug, click, Flask, pytz, six, aniso8601, Flask-restful, Flask-Script, marshmallow, flask-marshmallow, SQLAlchemy, marshmallow-sqlalchemy, urllib3, idna, certifi, chardet, requests, dogpile.cache,...
Code (markup):

Installing elasticsearch-HQ I have cannot import name 'Flask' error