hey guys I been trying to host a local server on port 22222 and when someone open it on the browser I get a msgbox saying yes / no - if you click yes it will accept the connection and show index.html basically, if you click no it will return nothing or something, anyway it works perfectly BUT
I'm trying to trigger a second msgbox after you click on the first one with a delay(after command), when you access the first time and click yes, it serves the page but the Established msg does not show up, if you refresh the page than it retriggers the Established msg and than ask again if you want to accept the connection (Bug Alert lol)
basiclly you need to run this code open 127.0.0.1:22222, click yes, than you will not see the its_ok msgbox, unless you do all this again
import sys
from http.server import HTTPServer, SimpleHTTPRequestHandler, test as Brain_Link
import tkinter
import tkinter.messagebox as mbox
window = tkinter.Tk()
window.wm_withdraw()
window.attributes("-topmost", True)
def Start_Brain_Link(*args):
Brain_Link(*args, port=22222)
def its_ok():
mbox.showinfo('A.I','Brain-Link Established!')
def its_bad():
mbox.showinfo('A.I','Brain-Link Attemp Blocked!')
class CORSRequestHandler(SimpleHTTPRequestHandler):
def end_headers (self):
if mbox.askquestion("Warning!", self.client_address[0]+" Requested Brain-Link!", icon='warning') == 'yes':
self.send_header('Access-Control-Allow-Origin', '*')
SimpleHTTPRequestHandler.end_headers(self)
window.after(1000,its_ok)
else:
window.after(1000,its_bad)
if __name__ == '__main__':
Start_Brain_Link(CORSRequestHandler, HTTPServer)
Related
I am making a server with Tkinter where it asks for the IP address you want to start the server on. when you jit enter it's supposed to close the window and start the server but the window doesn't close it just crashes(the server also starts though).
my code:
#!/usr/bin/env python3
import socket, threading, sys
import tkinter as tk
def sub(self):
global ip
ip = e1.get()
rw.quit()
rw = tk.Tk()
rw.title("IP")
rw.configure(bg="grey14")
rw.geometry("250x50")
hostname = socket.gethostname()
IPAddr = socket.gethostbyname(hostname)
e1 = tk.Entry(rw)
e1.bind("<Return>", sub)
e1.insert(0, IPAddr)
e1.pack(side=tk.LEFT)
b1 = tk.Button(rw, text="Submit", command=sub).pack(side=tk.RIGHT)
rw.mainloop()
please help!
(the server code is left out because StackOverflow says I'm not allowed to have that much code and this little text, but basically it starts another loop that accepts the clients)
You should use this command instead:
rw.destroy()
rw.quit() just bypasses the rw.mainloop() so that rw.mainloop() will still be running in the background. rw.destroy() stops it.
You are using sub(self)and on your Buttonyou have written just command=sub
So you have to write their
self.b1=tk.Button(rw,text="Submit",command=sub).pack(side=tk.RIGHT)
It's working I have run it
I am trying to make a simple program that opens the web browser when you go to a specific URL in flask.
I am using nginx with uwsgi, to work with flask, running on ubuntu desktop 18.04.
from flask import Flask
import webbrowser
app = Flask(__name__)
#app.route("/test")
def test():
#this is where a new webbrowser should be opened:
webbrowser.open_new_tab("https://google.com")
return "test!"
if __name__ == "__main__":
app.run(host='0.0.0.0')
I expect a new tab of the webbrowser to be opened on the server machine but nothing happens
Do you have a default browser set? You need a default set.
From webbrowser:
If the environment variable BROWSER exists, it is interpreted as the os.pathsep-separated list of browsers to try ahead of the platform defaults.
Another example from the same Python reference page demonstrates you need a window open to use open_new_tab() function:
Here are some simple examples:
url = 'http://docs.python.org/'
# Open URL in a new tab, if a browser window is already open.
webbrowser.open_new_tab(url)
# Open URL in new window, raising the window if possible.
webbrowser.open_new(url)
Ideally, You create a controller object specifying your browser of choice from the table in that link, such as "mozilla", "chrome", "safari" etc., then use the open_new_tab() function on that controller.
https://docs.python.org/3.5/library/webbrowser.html#browser-controller-objects
UPDATE:
So I tried this
import webbrowser
def main():
# this is where a new webbrowser should be opened:
webbrowser.open_new_tab("https://google.com")
return "test!"
if __name__ == "__main__":
main()
And I can open a new tab irrespective if a window is open.
So it works for a simple python script.
Are you saying that when you run you flask app, and try to do a GET request at http://yourip-or-domain-name/test your browser doesn't open?
(Assumption here is port 80 as you don't bind an explicit port in your app.run() call.
Okay, time for another question/post...
So currently i am trying to develop a simple python program that has a webkit/ webpage view and a serial port interface.. Not that it should matter, but this is also running on a raspberry pi.
The following code works fine.. But it will freeze the system as soon as i uncomment the serial port line that you can see commented out.
The day has been long and this one for some reason has my brain fried.. Python is not my strongest point, but mind you this is just a quick test script for now... Yes i have used google and other resources...
#!/usr/bin/env python
import sys
import serial
import threading
import time
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
sURL = ""
sURL2 = ""
objSerial = serial.Serial(0)
def SerialLooper():
global objSerial
if objSerial.isOpen() == True:
print("is_responding")
#objSerial.write("is_responding")
time.sleep(10)
SerialLooper()
class TestCLASS(object):
def __init__(self):
global sURL
global sURL2
global objSerial
objSerial = serial.Serial(0)
sURL = "http://localhost/tester"
app = QApplication(sys.argv)
webMain = QWebView()
webMain.loadFinished.connect(self.load_finished)
webMain.load(QUrl(sURL))
webMain.show()
thread = threading.Thread(target=SerialLooper)
thread.start()
sys.exit(app.exec_())
def load_finished(boolNoErrors):
global sURL
print("Url - " + sURL)
#something here
#something else here
newObjClass = TestCLASS()
EDIT
Futher on this, it appears its not the multithreading but the serial.write()
It has been a while since I used serial, but IIRC it is not threadsafe (on Windows at least). You are opening the port in the main thread and performing a write in another thread. It's a bad practice anyway. You might also consider writing a simple single-threaded program to see if the serial port is actually working.
PS Your program structure could use some work. You only need one of the global statements (global objSerial), the rest do nothing. It would be better to get rid of that one, too.
And the recursive call to SerialLooper() will eventually fail when the recursion depth is exceeded; why not just use a while loop...
def SerialLooper():
while objSerial().isOpen(): # Drop the == True
# print something
# write to the port
# Sleep or do whatever
I've been trying to perform communication between a kivy GUI module (my server) and another python module (my client). But so far I have problems running the xml rpc server along with the GUI run() function. I still have that problem even after running my server in a thread.
I hope someone has suggestions on how to fix my code, or just how to xml-rpc along with kivy.
Here is my code:
import kivy
kivy.require('1.7.1')
from kivy.lang import Builder
from kivy.uix.gridlayout import GridLayout
from kivy.app import App
from threading import Thread
from kivy.clock import Clock
Builder.load_file('kivy_gui.kv')
class RoamClientInterface(GridLayout):
"""
Sets up connection with XMLRPC server
"""
move = False
"""
driveForward() -> Moves robot forward
"""
def driveForward(self):
self.move = True
"""
stop() -> stops robot from moving
"""
def stop(self):
self.move = False
def returnBool(self):
return self.move
class ClientInterface(App):
def build(self):
return RoamClientInterface()
def sendCommands(dt):
print "start"
print ""
from SimpleXMLRPCServer import SimpleXMLRPCServer
server = SimpleXMLRPCServer(("localhost", 5000))
print "initialize server"
print ""
server.register_instance(RoamClientInterface())
print "register instance"
print ""
# while True:
try:
print "try handle request"
print ""
server.handle_request()
print "print handle request"
print ""
except KeyboardInterrupt:
import sys
sys.exit()
if __name__ == '__main__':
serverThread = Thread(target=sendCommands(4))
serverThread.start()
# Clock.schedule_once(sendCommands)
ClientInterface().run()
I got to solve the problem.
It is actually necessary to put it into a inside the RoamClientInterface to make it work, instead of putting it into my main function like I have it above.
I can give more detail info (show code) if anybody needs help
I'm writing my first desktop app and I'm struggling with class instances. This app is a simple ftp program using paramiko. What I've set up so far is a connection.py which looks like this...
#connect.py
import user, db
import paramiko, time, os
paramiko.util.log_to_file('paramiko-log.txt')
class Connection:
def __init__(self):
#Call DB Functions
database = db.Database()
#Set Transport
self.transport = paramiko.Transport((user.hostname, user.port))
#User Credentials
username = user.username
password = user.password
self.transport.connect(username = username, password = password)
self.sftp = paramiko.SFTPClient.from_transport(self.transport)
print "Set your credentials in user.py for now!"
msg = "Connecting as: %s, on port number %d" % (user.username, user.port)
print msg
def disconnect(self):
print "Closing connection..."
self.sftp.close()
self.transport.close()
print "Connection closed."
Pretty straightforward. Connect and disconnect.
This connect.py file is being imported into a main.py (which is my gui)
#main.py
import connect
from PySide import QtCore, QtGui
class Window(QtGui.QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
windowWidth = 550
windowHeight = 350
self.establishedConnection = ""
connectButton = self.createButton("&Connect", self.conn)
disconnectButton = self.createButton("&Disconnect", self.disconnect)
grid = QtGui.QGridLayout()
grid.addWidget(connectButton, 3, 3)
grid.addWidget(disconnectButton, 4, 3)
grid.addWidget(self.createList(), 1, 0, 1, 4)
self.setLayout(grid)
self.resize(windowWidth, windowHeight)
self.setWindowTitle("FTP Program")
def conn(self):
connection = connect.Connection()
self.establishedConnection = connection
def disconnect(self):
self.establishedConnection.disconnect()
def createButton(self, text, member):
button = QtGui.QPushButton(text)
button.clicked.connect(member)
return button
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
gui = Window()
gui.show()
sys.exit(app.exec_())
The issue is disconnecting.
I was thinking __init__ would create an instance of the Connection() class. If you look on main.py you can see that I tried to create the variable self.connectionEstablished in order to save the object so I could call disconnect on it later.
Where am I going wrong? I'm fairly new to python and other non-web languages(I spend most of my time writing RoR and php apps).
No errors are shown at any time and I started this app out as a terminal app so I do know that connect.py does work as intended.
Edit: So I guess Senderle got a connection closed message, which is what I'd like to see as well but I'm not. I'll mark a best answer if I see something that solves my problem.
Edit Solved: Pushed connect.py and main.py into one file to simplify things. And for some reason that solved things. So who knows whats going on. I'm still going to hold off on 'best answer'. If someone can tell me why I can't have a split file like that then I'm all ears.
I tried the code and it ran fine. I made only a few changes.
First, I didn't know what "user" and "db" are, so I commented out
import user, db
and
database = db.Database()
and used my own data for username, password, etc.
Second, the PySide module isn't available via my package manager, so I used PyQt4 instead. It didn't like grid.addWidget(self.createList(), 1, 0, 1, 4) so I commented that out, and everything worked as expected.
Further thoughts: When there were connection errors, there was some console feedback consisting of stack traces, but nothing more, and self.establishedConnection remained a string, causing self.establishedConnection.disconnect() to fail. So perhaps there's a connection problem?
EDIT: Aaaahhhhh, I just saw this: "No errors are shown at any time." Are you running this from a terminal or double-clicking an executable? If you start it from a terminal, I bet you'll see stacktraces in the terminal. The gui doesn't close when the code hits an exception.
EDIT2: If joining the files fixes the problem, then I am certain the problem cannot have anything to do with python itself. This has to be a problem with eclipse. You say that connection.py began as a terminal app, so you must be able to run python apps from the command line. Try the following: put main.py, connect.py, etc. in a directory of their own, open a terminal, and run python main.py. If it works as expected, then the problem has something to do with eclipse.
You are not calling conn() in the constructor.