How do you launch a Tkinter application from a django website - django

I created a Django website and I want to launch a tkinter program if the user clicks on a button. Can anyone tell me how to do that?
Any help is appreciated.

Generally, websites cannot cause other programs on the user's computer to run just by clicking a button on a webpage. The next-best thing is a specialized link that the client understands is associated with another installed application. See: How can I launch my windows app when a users opens a url?
If you happen to be running the django server on the same local system AND is running in the foreground by the same currently logged in user, you could also invoke a GUI program this way, as well for example using subprocess or os.system. Though, this would be quite an odd way to do this.
def my_view(): # Technically works, but in very limited practical use cases.
subprocess.Popen(['python', 'my-tk-app.py'])
Because tkinter also doesn't like to be run in any other thread besides the main thread, and other event loop-related issues, it's not really practical to invoke a tkinter app directly from a Django view, which usually will be running in a separate thread and needs to not be blocked.
For example, this would not work:
def my_view():
root.mainloop() # start the TK app
# fails because tk only wants to start in the main thread
# even if TK _could_ start, the view would eventually timeout
If you need a local tkinter app to also interface with a django server, you're almost always going to be better off by making your GUI app a client of the server -- that is to say, your tkinter app should use HTTP(S) or similar mechanism to communicate with Django.

Related

python-telegram-bot in django application

I’m trying to start python-telegram-bot in a web application with the django framework. To do this, I follow any example from the Telegram library and end up calling the method application.run_polling(). I know it’s not the best option because this blocks my web server, and I want to replace it with a better one, but I can’t find it.
According to official documentation, there is a tip that indicates the following:
When combining python-telegram-bot with other asyncio based frameworks, using this method is likely not the best choice, as it blocks the event loop until it receives a stop signal as described above. Instead, you can manually call the methods listed below to start and shut down the application and the updater. Keeping the event loop running and listening for a stop signal is then up to you.
And then I find the following section:
See also
initialize(), start(), stop(), shutdown() telegram.ext.Updater.start_polling(), telegram.ext.Updater.stop(), run_webhook()
I’ve tried to understand the methods in the list, but I can’t figure out how to run python-telegram-bot in the background and not affect my main server.
Are there any links or documents that expand the information or detail the steps to follow in these cases?
Thank you in advance
EDIT: Telegram I run it from an app configured in django as follows:
import asyncio
from django.apps import AppConfig
from telegram import Update
from telegram.ext import ContextTypes, Application, CommandHandler
from TaixTracking.configApp import ConfigApp
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await update.message.reply_text("Help!")
async def start_telegram():
application = Application.builder().token(ConfigApp().get_value('telegram', 'token', '')).build()
application.add_handler(CommandHandler("help", help_command))
await application.initialize()
await application.start()
await application.updater.start_polling()
print('Telegram load')
class CommunicationConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'communication'
def ready(self):
if not ConfigApp().is_telegram_launch():
ConfigApp().set_telegram_launch(True)
asyncio.run(start_telegram())

handling multiple users in a flask application

I have an simple login-based application that serves different pages to different users. Problem im facing here is when two users are logging in at once from two different systems. if user A comes in and B loggs in then when A refreshes his/her page user A can see What user B can see. does flask app not handle two processes at a time?
or should i just use another server on this for the support.
or is there a way i can implement threading for this purpose.
i found uwsgi but i have no idea about it but can it serve my purpose in any way?
Please help me on this i have been working on this for a month now and i could not find a legit answer for this one.
Use sessions , have strong app secret key and have a database such as SQLAlchemy

Interactive Shell on website in django

I have a Django project up and running. I'd like to provide a user to interactively use JDB through the web app to debug an application. I want that the user can issue a command such as
stop in [function name]
next
And that he would get the back the response and then can proceed.
When I use os.system however, like so:
def AttachDebugger(pid):
# enable port forwarding
adb = ADB()
adb.set_adb_path('~/Library/Android/sdk/platform-tools/adb')
adb.forward_socket('tcp:8001', 'jdwp:' + pid)
# attaching
os.system('jdb -connect com.sun.jdi.SocketAttach:hostname=localhost,port=8001')
then it opens up a JDB session in the background, but it freezes there and doesn't return control to the python code except stopping it via CTRL+C. Is there any way to provide such an interactive session?
What I would like to have is similar to the GITHUB-Tutorial-Page here:
https://try.github.io/levels/1/challenges/1
where the user can interact with the JDB instance
Thanks in advance.
I got it done with the pexpect module.

Django Admin Pages making my models unclickable

For some reason, my /admin page has made the models I defined un-editable. This is on my deployed server using apache and postgres. I'm logged in as a superuser and the is showing the links like this:
If I look at the same code locally in the development server connected to postgres, it looks like this:
Any idea what could be causing this?
** Update **
So it's not always blocked. I logged in today and I had access for a few actions (I cleaned some bogus email requests from my DB) but then after deleting some rows it got back to the read-only state.
Still no idea what's causing it.
home.models.py:
from django.db import models
from django import forms
from django.utils import timezone
class EmailRequest(models.Model):
email = models.EmailField()
created_date = models.DateTimeField(default=timezone.now())
class EmailRequestForm(forms.Form):
email = forms.EmailField()
home.admin.py:
from django.contrib import admin
from home.models import EmailRequest
class EmailRequestAdmin(admin.ModelAdmin):
list_display = ('email', 'created_date')
admin.site.register(EmailRequest, EmailRequestAdmin)
I don't have a direct answer to your problem, but I do have a few personal insights. First of all, using the Bitnami Django stack is probably a problem. I have used it a couple of times, and I never will again. The setup is definitely NOT ideal, and there is way too little documentation available for it to make your life any easier (wait, wasn't that the whole point of using a Bitnami stack?).
I would start looking through your logs (apache error log and postgres error logs specifically), I bet there is something in there that will point you in the correct direction.
I am sure you are running your development server from your local machine which is setup completely differently from the Bitnami stack. The better solution would be to install everything yourself on a barebones Ubuntu server. Then you will have much more familiarity with the setup.
THE BEST THING you can do, is go learn to use Vagrant. This will help you to maintain a local virtual machine instance, which is identical to your EC2 box. You will log into it using ssh just like the EC2 box, and you will be using it externally, just like the EC2 box. The closer you can get your development environment to your production environment, the easier debugging problems like this will be.
Hope that didn't make your life more difficult (seriously, if you get Vagrant running, your life will become MUCH easier)
See the following solution:
No access to models in admin panel with DEBUG=False
quote:
OK, I've found reason of my problems. It was caused by registering my
models in admin panel from files with models definitions. When I moved
all my registrations to one external file admin.py, then everything
works correctly.

Django application onload?

Is there a way to hook on the loading of the django application?
I want to be able to execute code when the application is loaded, so that I can for example
create static variables to be used later on by the application or establish connections to other servers.
The best I came across was to add code in the __init__.py file (How do I create application scope variable django?) but the problem with this solution is that I want my code to be executed after django has finished its startup process, and not in the middle/start of it.
Another solution I came up with is to have a view that handles this process and then when the application is deployed I issue a request to the url of the view. I don't like this solution very much, I prefer it to be a part of the loading of the application.
Any ideas of how to pull this out?
Thanks;
edit: Apllication refers to the entire django project and not one of the INSTALLED_APPS
Right now, there's really no good way to do this as Django doesn't have a startup signal. Interestingly, there is a ticket for this, but it's strangely tied to a branch that is being held up by another ticket. I'm not sure if Django 1.4 is feature-locked, yet, but as it's in release candidate stage, my bet is that it is. So, maybe you might get this in Django 1.5 whenever that happens.