zoukankan      html  css  js  c++  java
  • 使用bottle进行web开发(9):文件上传;json传递

    1.文件上传

       如果要完成文件上传,则需要对上文的form做一点改动,具体如下:

    <form action="/upload" method="post" enctype="multipart/form-data">
    Category: <input type="text" name="category" />
    Select a file: <input type="file" name="upload" />
    <input type="submit" value="Start upload" />
    </form>

    bottle把file的upload 是放在BaseRequest.files里的(以FileUpload进程的方式存在),这里,我们的例子,都是假设存在硬盘里的

    @route('/upload', method='POST')
    def do_upload():
    category = request.forms.get('category')
    upload = request.files.get('upload')
    name, ext = os.path.splitext(upload.filename)
    if ext not in ('.png','.jpg','.jpeg'):
    return 'File extension not allowed.'
    save_path = get_save_path_for_category(category)
    upload.save(save_path) # appends upload.filename automatically
    return 'OK'

    2)有些js或者REST的客户端,发送application/json 给服务器,通过这个方式来传递信息。这个时候,BaseRequest.json属性就保存这些信息。

    The raw request body
    You can access the raw body data as a file-like object via BaseRequest.body. This is a BytesIO buffer or a
    temporary file depending on the content length and BaseRequest.MEMFILE_MAX setting. In both cases the body
    is completely buffered before you can access the attribute. If you expect huge amounts of data and want to get direct
    unbuffered access to the stream, have a look at request[’wsgi.input’].

    3)WSGI环境

    每个的BaseRequest都保存着一个WSGI的环境字典。

    举例如下;

    @app.route('/my_ip')
    def get_remote_ip():
        ip=request.environ.get('REMOTE_ADDR')
        return template('Your IP is:{{IP}}',IP=ip)

    4)template

     bottle自带一个模板,称之为:SimpleTemplate Engine

     使用这个模板,可以通过template()函数或者view()装饰器。

    只需要把模板名称和要替换的参数信息传递进去即可。

    比如:

    @route('/hello')
    @route('/hello/<name>')
    def hello(name='World'):
    return template('hello_template', name=name)

    bottle去哪里找这些模板呢:去./VIEWS/目录下或者Bottle.template_path环境变量。

    Templates are cached in memory after compilation. Modifications made to the template files will have no affect until
    you clear the template cache. Call bottle.TEMPLATES.clear() to do so. Caching is disabled in debug mode.

  • 相关阅读:
    java设计模式之单例模式
    走台阶问题的递归方法与非递归方法
    QueenAttack
    为什么要建立数据仓库?
    通过复制现有的redhat虚拟机的文件,实现在VMWare8.0上重建一个新的redhat虚拟机环境
    hive配置以及在启动过程中出现的问题
    java_ee_sdk-7u2的安装与 启动
    Hadoop集群配置过程中需要注意的问题
    VMware8.0虚拟机中安装Ubuntu12.04使用NAT设置连接网络
    在VMware8.0.4安装centos6.3出现蓝屏,显示“anaconda: Fatal IO error 104 (Connection reset by peer) on X server :1.0. install exited abnormally [1/1]”?
  • 原文地址:https://www.cnblogs.com/aomi/p/7054242.html
Copyright © 2011-2022 走看看