zoukankan      html  css  js  c++  java
  • Flask添加七牛云上传文件图片系统

    Flask添加七牛云上传文件图片系统

    七牛云python sdk:https://developer.qiniu.com/kodo/sdk/1242/python

    在项目中添加七牛云图片上传系统

    首先你需要注册一个七牛云图片上传系统的账号,当然他们获取的个人信息相当多,如果不喜欢,可以用fdfs,但是我没找到fdfs在flask中配置的教程,不过也就是django中的迁移装饰器改一下,然后设置中改一下就行了。(当然也就是想想,其实那个迁移装饰器就写不来),所以既然没有办法装逼用fdfs,那就只能用七牛云来做了
    直接上代码
    这个放在我自己的utils文件夹中

    from qiniu import Auth,put_file,put_data,put_stream
    access_key='七牛云给你的ak'


    secret_key='七牛云给你的sk'

    def upload_file_qiniu(input_data):
    #create permission object
    创建认证对象
    q=Auth(access_key=access_key,secret_key=secret_key)
    你的储存库里的仓库名字
    bucket_name='cars'
    # generate upload token
    自动生成一个上传token
    token=q.upload_token(bucket=bucket_name)
    #upload file
    上传文件,返回值中会有图片路径信息和状态码
    ret1,ret2=put_data(token,None,data=input_data)
    print('this is result')
    print(ret1)
    print(ret2)
    #judge file upload is success or not
    用返回数据判断上传是否成功
    if ret2.status_code !=200:
    raise Exception('file upload failure')

    返回图片路径信息
    return ret1.get('key')
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    创建模块

    在我们之前的api文件夹下创建一个新模块,模块名任意,在模块蓝图中注册一下蓝图

    from flask import Blueprint
    # create blueprint
    api=Blueprint('api_1_0',__name__)

    from . import register,verify,cars
    1
    2
    3
    4
    5
    然后再在模块中导入api,然后再写一个蓝图路径装饰器

    from . import api
    允许装饰器内的视图函数使用post方法
    @api.route('/upload_image',methods=['post'])
    1
    2
    3
    配置常量表

    在之前创建的constants里面加上这些东西,主要是自定义状态码和七牛云图片查找路径前缀

    IMAGE_UUID_REDIS_EXPIRES=60
    PHONE_MSG_CODE_EXPIRES=2*60
    PHONE_FLAG_CODE_EXPIRES=2*60
    string_test_phonenum=r'^1[1234567890]{10}$'
    string_test_username=r'^[w]{6,18}$'
    string_test_email='^[A-Za-z0-9u4e00-u9fa5]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$'

    RETURN_OKAY=0 #no error report
    RETURN_LOGin=4001 #not login
    RETURN_IMAGE_INPUT_ERR=4002 #front website data aquired error
    RETURN_IMAGE_UPLOAD_ERR=4003 #front website data aquired error

    qiniu_url='http://puek1pi1o.bkt.clouddn.com/'
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17

    ---------------------

  • 相关阅读:
    类和对象基础
    《Python》常用内置模块
    《Python》内置方法进阶和常用模块
    《Python》反射、内置方法(__str__,__repr__)
    《Python》 property、classmethod、staticmethod、isinstance、issubclass
    《Python》 面向对象三大特性之多态、封装
    面向对象三大特性之继承
    面向对象初识(组合)
    面向对象之入门-《初识》
    前端基础之jQuery操作标签
  • 原文地址:https://www.cnblogs.com/hyhy904/p/11186723.html
Copyright © 2011-2022 走看看