I try to create a windows service to run my django project server. I can start the service, however, the server didn't run. So I cannot find the server on the chrome browser. My code is below.
And my based-code from this website https://metallapan.se/post/windows-service-pywin32-pyinstaller/.
Does anyone know what am I missing to create a service to run my Django server? Thanks in advance.
import os
import time
import sys
import win32serviceutil # ServiceFramework and commandline helper
import win32service # Events
import servicemanager # Simple setup and logging
# from django.views.decorators.csrf import ensure_csrf_cookie
class TestServiceForMeasurewarning:
"""Silly little application stub"""
def stop(self):
"""Stop the service"""
self.running = False
def run(self):
"""Main service loop. This is where work is done!"""
self.running = True
while self.running:
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_tutorial.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
# args = ['manage.py', 'runserver', '0.0.0.0:8002']
args = ['manage.py', 'runserver', '0.0.0.0:8003']
execute_from_command_line(args)
# execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
class MyServiceFramework(win32serviceutil.ServiceFramework):
_svc_name_ = 'Test Service For Measurementwarning'
_svc_display_name_ = 'MeasurementwarningTestingService'
def SvcStop(self):
"""Stop the service"""
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
self.service_impl.stop()
self.ReportServiceStatus(win32service.SERVICE_STOPPED)
def SvcDoRun(self):
"""Start the service; does not return until stopped"""
self.ReportServiceStatus(win32service.SERVICE_START_PENDING)
self.service_impl = TestServiceForMeasurewarning()
self.ReportServiceStatus(win32service.SERVICE_RUNNING)
# Run the service
self.service_impl.run()
def init():
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(MyServiceFramework)
servicemanager.StartServiceCtrlDispatcher()
else:
win32serviceutil.HandleCommandLine(MyServiceFramework)
if __name__ == '__main__':
init()
When the service manager executes SvcDoRun, __name__ will not be '__main__', so just remove that if statement. You can actually remove the main() function and just put the code in the service_impl function directly.
Related
How do I mock a cached value in Python unit test using cachetools ? I wrote a decorator named cache_controller. I had valid reasons not to use Cachetools' decorator.
When I try to mock TTLCache objects while writing the test code, I cannot mock it. What would be the reason ?
src/helpers/cache.py
from cachetools import TTLCache
total_cache = TTLCache(maxsize=1024, ttl=600)
src/wrappers/cache_controller.py
from functools import wraps
def cache_controller(cache, cache_args: tuple):
"""
:return: wrapper
"""
def decorator(func):
#wraps(func)
def wrapper(self, *args, **kwargs):
print("Cache in CACHE CONROLLER:", cache)
cache_key = tuple([kwargs[arg] for arg in cache_args])
print("Cache key in CACHE CONROLLER:", cache_key)
cached_value = cache.get(cache_key)
print("Cache value in CACHE CONROLLER:", cached_value)
if cached_value:
print(f"{self.__class__.__name__} : {cache_key} : from Local Cache : {cached_value}")
return cached_value
result = func(self, *args, **kwargs)
cache.update({cache_key: result})
print(f"{self.__class__.__name__} : {cache_key} : Updated to Local Cache : {result}")
return result
return wrapper
return decorator
src.run.py
from .wrappers.cache_controller import cache_controller
from .helpers.cache import total_cache
class ExampleClass(object):
#cache_controller(
cache=total_cache,
cache_args=("a", "b")
)
def example_method(self, a: int, b: int):
return a+b
*test/test_cache_controller.py
import unittest
from cachetools.ttl import TTLCache
from src.run import ExampleClass
from unittest import TestCase, mock
class TestCacheController(TestCase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def setUp(self):
self.fake_cache = TTLCache(maxsize=10, ttl=3600)
self.fake_cache.__setitem__((5, 6), 1)
self._class = ExampleClass()
def tearDown(self):
self._class = None
# mock.patch("src.run.total_cache")
def test_if_cache_filled(self, mock_total_cache):
mock_total_cache.return_value = self.fake_cache
result = self._class.example_method(a=5, b=6)
func_expected = 11
cache_expected = 1
print("Result:", result)
self.assertEqual(result, cache_expected)
if __name__ == '__main__':
unittest.main()
.. and run test code
cachetools-mock ❯ python -m test.test_cache_controller
Cache in CACHE CONROLLER: TTLCache([], maxsize=1024, currsize=0)
Cache key in CACHE CONROLLER: (5, 6)
Cache value in CACHE CONROLLER: None
ExampleClass : (5, 6) : Updated to Local Cache : 11
Result: 11
F
======================================================================
FAIL: test_if_cache_filled (__main__.TestCacheController)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/sumeyyeozkaynak/.pyenv/versions/3.7.5/lib/python3.7/unittest/mock.py", line 1255, in patched
return func(*args, **keywargs)
File "/Users/sumeyyeozkaynak/Desktop/.optiwisdom/workspace/cachetools-mock/test/test_cache_controller.py", line 28, in test_if_cache_filled
self.assertEqual(result, cache_expected)
AssertionError: 11 != 1
----------------------------------------------------------------------
Ran 1 test in 0.004s
FAILED (failures=1)
I've seen many replies that the arguments the decorators are getting are not mockable. It is correct because when the object is being tested after being mocked, the class is called again and the mocked object is overwrite.
If the import ExampleClass is imported in the Unit Test method under test, the problem will be eliminated.
import unittest
from unittest import TestCase, mock
class TestCacheController(TestCase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
#mock.patch.dict("src.helpers.cache.total_cache", {(5, 6): 1})
def test_if_cache_filled(self):
from src.run import ExampleClass
result = ExampleClass().example_method(a=5, b=6)
print("Result:", result)
self.assertEqual(result, 1)
if __name__ == '__main__':
unittest.main()
my project has many python files,and right now the problem is when I clicked button in Main-UI interface,it will invoke some function in another python file(sub-program),and i need all the running status in sub-program will also be updated in main-UI,how do i accomplish this?
The thing i can try so far i known is using socket,but i want to know do you guys have any other good ideas on this?
The code like this:
1. Main-UI:
import wx,time
from threading import Thread
from path import basicTest
EVT_RESULT_ID = wx.NewId()
def EVT_RESULT(win, func):
win.Connect(-1, -1, EVT_RESULT_ID, func)
class ResultEvent(wx.PyEvent):
def __init__(self, data):
wx.PyEvent.__init__(self)
self.SetEventType(EVT_RESULT_ID)
self.data = data
class TestThread(Thread):
def __init__(self, wxObject):
Thread.__init__(self)
self.wxObject = wxObject
self.start()
def run(self):
this masked sub-script can run,but what i want to do is to replace it with invoking from another python file
'''
for i in range(6):
time.sleep(1)
wx.PostEvent(self.wxObject, ResultEvent(i))
'''
data = basicTest().run(10)
wx.PostEvent(self.wxObject, ResultEvent(data))
class MyForm(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Tester")
panel = wx.Panel(self, wx.ID_ANY)
self.btn = wx.Button(panel, label="Start Test")
self.statusbar = self.CreateStatusBar()
self.btn.Bind(wx.EVT_BUTTON, self.onButton)
EVT_RESULT(self, self.updateStatus)
def onButton(self, event):
TestThread(self)
btn = event.GetEventObject()
btn.Disable()
def updateStatus(self, msg):
t = msg.data
self.statusbar.SetStatusText("Sequence %i running.." %t)
self.btn.Enable()
if __name__ == "__main__":
app = wx.PySimpleApp()
frame = MyForm().Show()
app.MainLoop()
sub-script:
import time
class basicTest():
def run(self,inter):
for i in range(inter):
return i
time.sleep(1)
As list above and also i known that the main UI only updated when the sub-script finished,it's not run-time refresh from another sub,can anyone help me, very appreciate
I would just leave the long running code in its thread. Then you can have wxPython start the thread. In your thread's run method, just use one of wxPython's thread-safe methods to call your UI. I would recommend wx.CallAfter or 'wx.PostEvent'.
Once you have that done, then you just execute the necessary method in your main UI.
I am trying to write my first wxpython GUI program,in my program,I want to get anothor software window's title,if the title change,clear the old title and show the new title in GUI,I test in cmd,it can get the title in a loop,but I don't konw how to set a event in GUI to update the title.
my code:
def getinfos():
tempWindowName=win32gui.GetWindowText (find_window())
while True:
titles=[]
if (tempWindowName==win32gui.GetWindowText (find_window())):
pass
else:
tempWindowName=win32gui.GetWindowText (find_window())
titles.append(tempWindowName)
return title[0]
time.sleep(1000)
and the GUI code:
import controller2
import time
########################################################################
class InfoPanel(wx.Panel):
#----------------------------------------------------------------------
def __init__(self, parent):
"""Constructor"""
wx.Panel.__init__(self, parent)
try:
self.titleResults = controller2.getinfos()
except:
self.titleResults = 'no data'
mainSizer = wx.BoxSizer(wx.VERTICAL)
self.titlecontent = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE|wx.TE_RICH|wx.TE_LEFT|wx.TE_WORDWRAP|wx.NO_BORDER)
self.titlecontent.SetBackgroundColour('white')
self.settitle()
mainSizer.Add(self.yejicontent, 2.5, wx.ALL|wx.EXPAND, 5)
self.SetSizer(mainSizer)
#----------------------------------------------------------------------
def settitle(self):
self.titlecontent.SetValue("%s"%self.titleResults)
########################################################################
class InfoFrame(wx.Frame):
""""""
#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
wx.Frame.__init__(self, None, title="title",size=(500, 880))
panel = InfoPanel(self)
style= self.GetWindowStyle()
self.SetWindowStyle(style|wx.STAY_ON_TOP)
class MyApp(wx.App):
def OnInit(self):
self.infoFrame=InfoFrame()
self.SetTopWindow(self.infoFrame)
self.infoFrame.Show(True)
return True
#----------------------------------------------------------------------
if __name__ == "__main__":
app = MyApp(False)
app.MainLoop()
Thanks for your time and appreciate for any advise.
Put the getinfos function/method into a thread. When the title changes, have the thread use wx.CallAfter or wx.PostEvent (both of which are thread-safe) to tell the GUI to update. If you don't put it into a thread, you're GUI will be very unresponsive.
http://wiki.wxpython.org/LongRunningTasks
http://www.blog.pythonlibrary.org/2010/05/22/wxpython-and-threads/
Pubsub rocks, but won't work in this case if you're running that getinfos function in your wxPython main loop as it will block it. You could use pubsub in the thread in combination with those threadsafe methods I mentioned though.
You can send a custom wx event or setup pubsub.
Ok, why this simple app dosn't work.
I've spent one day investigating this and got nothing.
import wx, os
import gtk
import keybinder
class FrameWithHotKey(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
keybinder.bind("<Ctrl>period", self.toggle_shown)
def toggle_shown(self):
# windowNow id
if self.IsShown():
self.Hide()
else:
self.Show()
self.Raise()
if __name__ == '__main__':
app = wx.PySimpleApp()
frame = FrameWithHotKey(None)
app.MainLoop()
I don't know why, but sometimes (especially when I raise apps by clicking on them on panel) raising dosen't work and I got flash icon instead of raised window.
UPDATE
Ok, i return to the topic and notice these..
above example works for me.. strange
i isolated strange behaviour which below code shows.. it's something related with wnck lib. So if my app window is deactivated by open new window (left click on window - test1) then raise works perfect, but if other window (replace 'opera' with any of Yours) is activated with wnck(by right click - test2) then actvation fails
import logging
import subprocess
import time
import wnck
import wx
logging.basicConfig(level=logging.DEBUG)
class MyFrame(wx.Frame):
def __init__(self, parent, title=''):
wx.Frame.__init__(self, parent, title=title)
self.Centre()
self.Bind(wx.EVT_LEFT_DOWN, self.test1)
self.Bind(wx.EVT_RIGHT_DOWN, self.raise_window)
def test1(self, evt):
logging.debug('losing..')
subprocess.Popen(['xterm'])
time.sleep(1)
self.Raise()
logging.debug('lost')
def lose_focus_by_wnck(self):
screen = wnck.screen_get_default()
import gtk
while gtk.events_pending():
gtk.main_iteration(False)
wins = screen.get_windows()
logging.debug('wins: {0}'.format(wins))
for win in wins:
app_name = win.get_application().get_name()
logging.debug('app: {0}'.format(app_name))
if 'opera' in app_name.lower():
win_id = win.get_xid()
break
else:
win_id = None
return win_id
def test2(self, evt):
logging.debug('losing..')
win_id = self.lose_focus_by_wnck()
win = wnck.window_get(win_id)
TIMESTAMP = 0
win.activate(TIMESTAMP)
logging.debug('lost')
time.sleep(1)
self.Raise()
logging.debug('raised')
if name == 'main':
app = wx.PySimpleApp(redirect=False)
frame = MyFrame(None)
frame.Show()
app.MainLoop()
Does anybody understand this behaviour instead of very helpful wtf like i feel? :)
What is keybinder? Are you using an AcceleratorTable? See http://www.blog.pythonlibrary.org/2010/12/02/wxpython-keyboard-shortcuts-accelerators/ for more info. I don't think you can mix pyGtk with wxPython.
ubuntu 10.04, KDE 4.4.5
python 2.6.4
qt 4.6.2
pyqt 4.6.2
I'm trying to create a QCompleter, which works fine if I just build the QLineEdit.
However if I drop the QLineEdit into a QMainWindow, the QCompleter no longer works.
Here is the LineEdit class
# LineEdit class
import sys
from PyQt4 import QtCore, QtGui
class LineEdit(QtGui.QLineEdit):
def __init__(self, parent=None):
super(LineEdit, self).__init__(parent)
self.setFocusPolicy(QtCore.Qt.StrongFocus)
self.completer = QtGui.QCompleter(self)
self.completer.setCompletionMode(QtGui.QCompleter.UnfilteredPopupCompletion)
self.pFilterModel = QtGui.QSortFilterProxyModel(self)
self.pFilterModel.setFilterCaseSensitivity(QtCore.Qt.CaseInsensitive)
self.completer.setPopup(self.view())
self.setCompleter(self.completer)
self.textEdited[unicode].connect(self.pFilterModel.setFilterFixedString)
def setModel(self, model):
self.pFilterModel.setSourceModel(model)
self.completer.setModel(self.pFilterModel)
def setModelColumn( self, column ):
self.completer.setCompletionColumn(column)
self.pFilterModel.setFilterKeyColumn(column)
def view(self):
return self.completer.popup()
def index( self ):
return self.currentIndex()
The QCompleter works if I build LinEdit this way
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
model = QtGui.QStandardItemModel()
for i,word in enumerate(['test', 'blah', 'heh', 'yep']):
item = QtGui.QStandardItem(word)
model.setItem(i, 0, item)
lineEdit = LineEdit()
lineEdit.setModel(model)
lineEdit.setModelColumn(0)
lineEdit.show()
sys.exit(app.exec_())
This compiles fine, but no longer shows the QCompleter
if __name__ == '__main__':
class Example(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.centralWidget = QtGui.QWidget(self)
self.layout = QtGui.QVBoxLayout(self.centralWidget)
# can I push this inside the LineEdit class instead?
model = QtGui.QStandardItemModel()
for i, word in enumerate(['test', 'blah', 'heh', 'yep', 'hello', 'hi']):
item = QtGui.QStandardItem(word)
model.setItem(i, 0, item)
# Make a LineEdit instance
self.lineEdit = LineEdit(parent=self.centralWidget)
self.lineEdit.setModel(model)
self.lineEdit.setModelColumn(0)
self.layout.addWidget(self.lineEdit)
self.setCentralWidget(self.centralWidget)
app = QtGui.QApplication(sys.argv)
QtWin = Example()
QtWin.show()
sys.exit(app.exec_())
turned out to be quite simple really, hopefully this will help anyone else using PyQt's QCompleter for auto-completion
import sys
from PyQt4 import QtCore, QtGui
class LineEdit(QtGui.QLineEdit):
def __init__(self, parent, completerContents):
super(LineEdit, self).__init__(parent)
self.completerList = QtCore.QStringList()
for content in completerContents:
self.completerList.append(QtCore.QString(content))
self.completer = QtGui.QCompleter(self.completerList, self)
self.completer.setCompletionMode(QtGui.QCompleter.PopupCompletion)
self.completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
self.setCompleter(self.completer)
if __name__ == '__main__':
class Example(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.centralWidget = QtGui.QWidget(self)
self.layout = QtGui.QVBoxLayout(self.centralWidget)
# Example LineEdit Call
self.lineEdit = LineEdit(parent=self.centralWidget, completerContents=('test', 'blah', 'heh', 'yep', 'hello', 'hi'))
self.layout.addWidget(self.lineEdit)
self.setCentralWidget(self.centralWidget)
app = QtGui.QApplication(sys.argv)
QtWin = Example()
QtWin.show()
sys.exit(app.exec_())
There is possible 2 reasons of such a behavior in the second case:
Your completer has no completion model in the second case
Your LineEdit has set other completer
Don't know if U can to debug this and set breakpoint on QLineEdit::setCompleter in python.