How can I get Bottle to restart on file change?

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-29 16:05:55

问题


I'm really enjoying Bottle so far, but the fact that I have to CTRL+C out of the server and restart it every time I make a code change is a big hit on my productivity. I've thought about using Watchdog to keep track of files changing then restarting the server, but how can I do that when the bottle.run function is blocking.

Running the server from an external script that watches for file changes seems like a lot of work to set up. I'd think this was a universal issue for Bottle, CherryPy and etcetera developers.

Thanks for your solutions to the issue!


回答1:


Check out from the tutorial a section entitled "Auto Reloading"

During development, you have to restart the server a lot to test your recent changes. The auto reloader can do this for you. Every time you edit a module file, the reloader restarts the server process and loads the newest version of your code.

This gives the following example:

from bottle import run
run(reloader=True)



回答2:


With

run(reloader=True)

there are situations where it does not reload like when the import is inside a def. To force a reload I used

subprocess.call(['touch', 'mainpgm.py'])

and it reloads fine in linux.




回答3:


Use reloader=True in run(). Keep in mind that in windows this must be under if __name__ == "__main__": due to the way the multiprocessing module works.

from bottle import run

if __name__ == "__main__":
    run(reloader=True)



回答4:


These scripts should do what you are looking for.

AUTOLOAD.PY

import os
def cherche(dir):
    FichList = [ f for f in os.listdir(dir) if os.path.isfile(os.path.join(dir,f)) ]
    return FichList

def read_file(file):
    f = open(file,"r")
    R=f.read()
    f.close()
    return R

def load_html(dir="pages"):
    FL = cherche(dir)
    R={}
    for f in FL:
        if f.split('.')[1]=="html":
            BUFF = read_file(dir+"/"+f)
            R[f.split('.')[0]] = BUFF
    return R 

MAIN.PY

# -*- coding: utf-8 -*-

#Version 1.0 00:37


import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import datetime
import ast
from bottle import route, run, template, get, post, request, response, static_file, redirect

#AUTOLOAD by LAGVIDILO
import autoload
pages = autoload.load_html()




BUFF = ""
for key,i in pages.iteritems():
    BUFF=BUFF+"@get('/"+key+"')\n"
    BUFF=BUFF+"def "+key+"():\n"
    BUFF=BUFF+" return "+pages[key]+"\n"

print "=====\n",BUFF,"\n====="
exec(BUFF)


run(host='localhost', port=8000, reloader=True)


来源:https://stackoverflow.com/questions/11004204/how-can-i-get-bottle-to-restart-on-file-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!