Flask相关用法

1,Flask安装

http://docs.jinkan.org/docs/flask/installation.html

2,Flask文件上传和下载

https://www.cnblogs.com/mosson/p/6163233.html#_label0

3,Flask中传递参数

### 传递参数:
传递参数的语法是:`/<参数名>/`。然后在视图函数中,也要定义同名的参数。例如:
@app.route('/article/<string:test>/')
# 传递的参数名是test,因此就需要在函数的形参中定义同名的参数test
def test_article(test):
    return 'test_article:{}'.format(test)

### 参数的数据类型:
1. 如果没有指定具体的数据类型,那么默认就是使用`string`数据类型。
2. `int`数据类型只能传递`int`类型。
限制参数:<int:article_id>,如果在浏览器中访问:http://127.0.0.1:5000/p/11111.0/
那就找不到报not found错误,因为我限制了是整形,你现在是浮点型,同理,如果你是浮点型,我使用
整形访问,那就又访问不到了

3. `float`数据类型只能传递`float`类型。

4. `path`数据类型和`string`有点类似,都是可以接收任意的字符串,
但是`path`可以接收路径,也就是说可以包含斜杠。
@app.route('/article/<path:test>/') path数据类型
def test_article(test):
    return 'test_article:{}'.format(test)

5. `uuid`数据类型只能接收符合`uuid`的字符串。`uuid`是一个全宇宙都唯一的字符串,
一般可以用来作为表的主键。

6.`any`数据类型可以在一个`url`中指定多个路径。例如:
@app.route('/<any(blog,article):url_path>/<id>/')
    def detail(url_path,id):
        if url_path == 'blog':
            return '博客详情:%s' % id
        else:
            return '博客详情:%s' % id

 4,Flask通过查询字符串的形式传递参数

#就是通过`?key=value`的形式传递的
# 通过问号的形式传递参数,例如百度:http://127.0.0.1:5000/d/?wd=%E7%AE%80%E4%B9%A6&pn=20
@app.route('/d/')
def d():
    wd = request.args.get("wd")
    page_number = request.args.get("pn")
    return "通过字符串查询的关键字为:{}, 页码为:{}".format(wd, page_number)

#针对这种情况,服务端使用reqeust.args来获取问号形式的查询字符串中参数的值。

 5,Flask获得端iP地址的方式

ip = request.remote_addr

 6, Flask获得服务器iP地址方式

ip = request.host

 7, Flask接收JSON文件的方法

#1,利用flask的request.form.get()方法
@app.route('/sendjson', methods=['POST'])
def sendjson():

# 接受前端发来的数据
data = json.loads(request.form.get('data'))

# lesson: "Operation System"
# score: 100
lesson = data["lesson"]
score = data["score"]

# 自己在本地组装成Json格式,用到了flask的jsonify方法
info = dict()
info['name'] = "pengshuang"
info['lesson'] = lesson
info['score'] = score
return jsonify(info)


JS:
<script>
    $(document).ready(function () {
    var data = {
         data: JSON.stringify({"lesson": "Operation System", "score": 100})
   }
      $.ajax({
        url:"/sendjson",
        type: 'POST',
        data: data,
        success: function (msg) {
            alert(msg.name)
        }
    })
  });
</script>

#2,利用flask的request.get_data()方法
@app.route('/sendjson2',methods=['POST'])
def sendjson2():

# 接收前端发来的数据,转化为Json格式,我个人理解就是Python里面的字典格式
data = json.loads(request.get_data())

# 然后在本地对数据进行处理,再返回给前端
name = data["name"]
age = data["age"]
location = data["location"]
data["time"] = "2016"

# Output: {u'age': 23, u'name': u'Peng Shuang', u'location': u'China'}
# print data
return jsonify(data)

JS:
<script>
    $(document).ready(function () {
        var student = new Object();
        student.name = "Peng Shuang";
        student.age = 23;
        student.location = "China";
        var data = JSON.stringify(student)

    $.ajax({
        url: "/sendjson2",
        type: "POST",
        data: data,
        success: function (msg) {
            alert(msg.time)
        }
    })
    })
</script>

 附Objective c 端传递JSON数据代码:

方案一 : 把JSON格式的字符串序列化成JSON的二进制
- (void)POSTJSON_01
{
    NSString *jsonStr = @"{\"name\":\"大发明家\"}";
 
    // 把JSON格式的字符串序列化成JSON的二进制
    NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    [self postJsonWith:jsonData];
}


方案二 : 把字典序列化成JSON格式的二进制
- (void)POSTJSON_02
{
    NSDictionary *dict = [NSDictionary dictionaryWithObject:@"亚索" forKey:@"name"];
 
    // 把字典序列化成JSON格式的二进制
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
    [self postJsonWith:jsonData];
}


方案三 : 把数组序列化成JSON格式的二进制
- (void)POSTJSON_03
{
    NSDictionary *dict1 = [NSDictionary dictionaryWithObject:@"牛头" forKey:@"name"];
    NSDictionary *dict2 = [NSDictionary dictionaryWithObject:@"石头人" forKey:@"name"];
    NSArray *arr = @[dict1,dict2];
 
    // 把数组序列化成JSON格式的二进制
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:0 error:NULL];
    [self postJsonWith:jsonData];
}


发送json数据到服务器的主方法,传入json数据的二进制
- (void)postJsonWith:(NSData *)jsonData
{
    // URL
    NSURL *URL = [NSURL URLWithString:@"http://localhost/php/upload/postjson.php"];
    // 请求
    NSMutableURLRequest *requestM = [NSMutableURLRequest requestWithURL:URL];
    // 设置请求方法
    requestM.HTTPMethod = @"POST";
    // 设置请求体
    requestM.HTTPBody = jsonData;
 
    // 发送请求
    [[[NSURLSession sharedSession] dataTaskWithRequest:requestM completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        // 处理响应
        if (error == nil && data != nil) {
 
            // 反序列化
            NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@",str);
 
        } else {
            NSLog(@"%@",error);
        }
    }] resume];
}

猜你喜欢

转载自www.cnblogs.com/wayne-zhang/p/10594255.html