python - 解决方案不起作用 - 错误状态:平台不允许使用不安全的 HTTP
问题描述
我正在尝试使用flutter作为前端和python作为后端来编写一个应用程序。我正在用python创建一个rest api,现在尝试用flutter向它发送请求。
在颤振中运行附加代码时出现以下错误: SocketException: OS Error: Connection denied, errno = 111, address = 127 .0.0.1, port = 43360
我尝试使用 IPv4 的地址切换本地主机并得到错误:错误状态:平台不允许不安全的 HTTP:http://IPv4_adress:5000/product/1。
我尝试了我在网上找到的所有解决方案,比如添加到 myapp\android\app\src\debug\AndroidManifest.xml :
<application android:usesCleartextTraffic="true">
</application>
我还尝试将 HTTP 更改为 HTTPS,但我只收到错误消息:SocketException: OS Error: Connection timed out, errno = 110, address = 10.100.102.15, port = 59658
我重新加载了应用程序,但错误仍然存在。
我使用了此链接https://flutter.dev/docs/cookbook/networking/fetch-data中的指南,它运行良好。在我将专辑类更改为产品类并将 url 更改为我的 rest api url 后发生错误。我使用带有flask和sqlalchemy的python创建了rest api,我可以使用邮递员和chrome向它发送请求。
颤振代码:
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<Product> fetchProduct() async {
final response = await http.get(Uri.parse('http://127.0.0.1:5000/product/1'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Product.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load Product');
}
}
class Product {
final int id;
final String name;
final String description;
final double price;
final int qty;
Product({
@required this.id,
@required this.name,
@required this.description,
@required this.price,
@required this.qty,
});
factory Product.fromJson(Map<String, dynamic> json) {
return Product(
id: json['id'],
name: json['name'],
description: json['description'],
price: json['price'],
qty: json['qty'],
);
}
}
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Future<Product> futureProdcut;
@override
void initState() {
super.initState();
futureProdcut = fetchProduct();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: const Text('Fetch Data Example'),
),
body: Center(
child: FutureBuilder<Product>(
future: futureProdcut,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.name);
} else if (snapshot.hasError) {
print(snapshot.error);
return Text('${snapshot.error}');
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
),
),
),
);
}
}
Python代码:
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
# init app
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
#database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'db.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Init db
db =SQLAlchemy(app)
# Init ma
ma = Marshmallow(app)
#Product Class/model
class Product(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), unique=True)
description = db.Column(db.String(200))
price = db.Column(db.Float)
qty = db.Column(db.Integer)
def __init__(self, name, description, price, qty):
self.name = name
self.description = description
self.price = price
self.qty = qty
# Product Schema
class ProductSchema(ma.Schema):
class Meta:
fields = ('id', 'name', 'description', 'price', 'qty')
# Init Schema
product_schema = ProductSchema()
products_schema = ProductSchema(many=True)
# Create a Product
@app.route('/product', methods=['POST'])
def add_product():
name = request.json['name']
description = request.json['description']
price = request.json['price']
qty = request.json['qty']
new_product = Product(name, description, price, qty)
db.session.add(new_product)
db.session.commit()
return product_schema.jsonify(new_product)
# Get All Products
@app.route('/product', methods=['GET'])
def get_prodcuts():
all_products = Product.query.all()
result = products_schema.dump(all_products)
print(result)
print(type(result))
return jsonify(result)
# Get Single Products
@app.route('/product/<id>', methods=['GET'])
def get_prodcut(id):
product = Product.query.get(id)
return product_schema.jsonify(product)
# Update a Product
@app.route('/product/<id>', methods=['PUT'])
def update_product(id):
product = Product.query.get(id)
name = request.json['name']
description = request.json['description']
price = request.json['price']
qty = request.json['qty']
product.name = name
product.description = description
product.price = price
product.qty = qty
db.session.commit()
return product_schema.jsonify(product)
# run server
if __name__ == '__main__':
app.run(debug=True)
解决方案
推荐阅读
- python - 两条曲线 y_1 和 y_2 之间的填充区域不共享相同的 x
- c++ - 从文件中读取二维数组并将其传递给另一个函数
- python - 在 for 循环中取数据帧的交集
- graphql - GraphQLError:语法错误:预期名称,找到
- android - 数据绑定错误****msg:无法解析为属性的访问器或侦听器
- javascript - 这两个将函数分配给 const 的表达式有什么区别?
- angular - Ngrx TypeError:无法将未定义转换为对象
- unix - 用于硬编码密码的 Unix Grep
- c++ - VTK 纹理比例
- javascript - 如何将 js onclick 函数与数据绑定一起使用?[框架7]