zoukankan      html  css  js  c++  java
  • 用 bottle.py 写了个简单的升级包上传

    可以当作一个 demo 来玩吧,在这里分享一下。里面涉及的内容包含了文件上传,cookie 设置和读取,重定向(redirect)。

    from bottle import run, post, get, request, response, redirect
    import os
    
    login_page='''
        <b>Sorry! Authentication is needed!</b>
        <form action='/login' enctype="multipart/form-data" method='post'>
        <fieldset>
        <legend>Input passwd for Admin:</legend>
        <label>passwd:</label>
        <input type="password" name="passwd"/>
        <input type='submit' value='submit'>
        </fieldset>
        </form>
        '''
    upload_page='''
        <!DOCTYPE html>
        <html>
        <head>
        <title>
        Firmware Update
        </title>
        </head>
        <body>
        <form action='/upload' enctype="multipart/form-data" method='post'>
        <fieldset>
        <legend>Firmware Update:</legend>
        <label>Select the file:</label>
        <input type="file" name="upload"/>
        <input type='submit' value='submit'>
        </fieldset>
        </form>
        </body>
        </html>
        '''
        
    @get('/')
    def home():
        usr = request.get_cookie("account")
        if usr:
            redirect('/upload')
        else:
            return login_page
    
    @post('/login')
    def login():
        passwd = request.POST['passwd']
           
        if passwd == '88888888':
            response .set_cookie("account", 'admin')
            redirect('/upload')
        else:
            return 'wrong! go back & retry!'
    
    @get('/upload')
    def upload():
        usr = request.get_cookie("account")
        if usr:
            return upload_page
        else:
            redirect('/')
    
    @get('/logout')
    def logout():
        response.delete_cookie("account")
        redirect('/')
    
    @post('/upload')
    def do_upload():
        usr = request.get_cookie("account")
        if usr:
            upload = request.files.get('upload')
            name, ext = os.path.splitext(upload.filename)
            if ext not in ('.tgz','.gz'):
                return 'You give a wrong file. Retry!'
            
            save_path = "/opt/myapp/update.tar.gz"
            with open(save_path, 'w') as open_file:
                open_file.write(upload.file.read())
    
            return '''
            <b>Done! Please re-power the machine to fill the update! </b>
            <a href="/logout" title="logout">logout</a>
            '''
        else:
            redirect('/')
    
    run(host='192.168.1.230', port=80)
  • 相关阅读:
    Python的with语句(文件打开方式)
    python代码异常范围检查方法(非常实用)
    python一标准异常总结大全(非常全)
    python里pickle模块
    pyhon文件操作典型代码实现(非常经典!)
    codeblocks中cocos2dx项目添加新的.cpp和.h文件后编译运行的方法
    ubuntu安装cocos2dx
    学习资料整理
    Spring学习笔记--在SpEL中筛选集合
    Spring学习笔记--Spring表达式语言SpEL
  • 原文地址:https://www.cnblogs.com/pied/p/6497241.html
Copyright © 2011-2022 走看看