StackOverflow
I have a little problem with kivy when I'm trying to load a pic from atlas:
D:\Games\Projects\python>py -2 test.py
[INFO ] [Logger ] Record log in C:\Users\%username%\.kivy\logs\kivy_18-03-05_70.txt
[INFO ] [Kivy ] v1.10.0
[INFO ] [Python ] v2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:25:58) [MSC v.1500 64 bit (AMD64)]
[INFO ] [Factory ] 194 symbols loaded
[INFO ] [Image ] Providers: img_tex, img_dds, img_sdl2, img_gif (img_pil, img_ffpyplayer ignored)
[INFO ] [Text ] Provider: sdl2
[DEBUG ] [App ] Loading kv <.\my.kv>
[DEBUG ] [App ] kv <.\my.kv> not found
[DEBUG ] [Atlas ] Load <images\a.atlas>
[DEBUG ] [Atlas ] Need to load 1 images
[DEBUG ] [Atlas ] Load <images\a-0.png>
[DEBUG ] [ImageSDL2 ] Load <D:\Games\Projects\python\images\a-0.png>
[TRACE ] [Image ] u'D:\\Games\\Projects\\python\\images\\a-0.png', populate to textures (1)
a.atlas:
{
"a-0.png": {
"logo": [1291, 728, 326, 93],
"jill": [0, 0, 644, 364]
}
}
test.py:
# -*- coding: utf-8 -*-
from kivy import resources
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.graphics import Color, Rectangle
from kivy.atlas import Atlas
from kivy.uix.image import Image
from kivy.config import Config
Config.set('graphics', 'width', '1280')
Config.set('graphics', 'height', '720')
Config.set('kivy', 'log_level', 'trace')
class MyApp(App):
def build(self):
tt = Atlas('./images/a.atlas')
return Image(source='atlas://images/a/logo', pos=[100, 100], size=[326, 93])
if __name__ == '__main__':
MyApp().run()
Now it's just a test. I am trying to learn kivy, but something going wrong
Anyone knows why this can happening?
This is a bug, and as one of the comments indicates:
i think the issue is that the saving in its current form requires the
creation of a texture, and in this test, it happens that no opengl
context have been created, a simple workaround is to add:
from kivy.core.window import Window or
from kivy.base import EventLoop EventLoop.ensure_window() at the top
of the script.
It works for me after that.
I don't think it's actually a bug, since we don't promise image
manipulation without the creation of an opengl context, but maybe we
could call ensure_window() in Image.save().
So you should only use the following:
# -*- coding: utf-8 -*-
from kivy.app import App
from kivy.atlas import Atlas
from kivy.uix.image import Image
from kivy.core.window import Window
class MyApp(App):
def build(self):
tt = Atlas('images/a.atlas')
return Image(texture=tt["logo"], pos=[100, 100], size=[326, 93])
if __name__ == '__main__':
MyApp().run()
Also if you do not want to use that you can eliminate the use of Atlas:
# -*- coding: utf-8 -*-
from kivy.app import App
from kivy.uix.image import Image
class MyApp(App):
def build(self):
return Image(source='atlas://images/a/logo', pos=[100, 100], size=[326, 93])
if __name__ == '__main__':
MyApp().run()
Related
I am creating an api where two endpoints are using the ws(s) protocol.
As my API is behind Google endpoint, Every endpoint needs to be defined onto an OpenApi2.0 file.
To create this definition I use drf-yasg.
I have a routing. py file like this:
""" systems/routing.py"""
from django.urls import path
from .consumers.list_sessions_consumer import MyFirstConsumer
from .consumers.session_consumer import MySecondConsumer
urlpatterns = [
path(r'v1/ws/yo/<str:uuid>/sessions-sumpup', MyFirstConsumer.as_asgi()),
path(r'v1/ws/yo/<str:uuid>/sessions', MySecondConsumer.as_asgi()),
]
and I register it onto my asgi.py file like this:
# pylint: skip-file
""" main/asgi.py """
import os
import django
from django.core.asgi import get_asgi_application
django_asgi_app = get_asgi_application()
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'main.settings')
django.setup()
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from systems.websockets.routing import urlpatterns as system_websocket_url
application = ProtocolTypeRouter({
"http": django_asgi_app,
"websocket": AuthMiddlewareStack(
URLRouter(
system_websocket_url
)
),
})
Don't mind the import order this is due to this error: Django apps aren't loaded yet when using asgi
So my socket works as expected, now, I want my command line: python3 manage.py generate_swagger swagger.yaml to add these new endpoint to my swagger file.
I tried to directly add my url to the same object then all my other urls like so:
urlpatterns = [
path(r'v1/toto/<str:uuid>', MyView.as_view()),
...,
path(r'v1/ws/yo/<str:uuid>/sessions-sumpup', MyFirstConsumer.as_asgi()),
path(r'v1/ws/yo/<str:uuid>/sessions', MySecondConsumer.as_asgi()),
]
But nothing shows up in my swagger file.
Any ideas ?
Thanks
I got this error: ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path)
Here is my routing.py:
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator
from channels.auth import AuthMiddlewareStack
from django.urls import path
from messanger.contacts.consumers import ChatConsumer
application = ProtocolTypeRouter({
# Empty for now (http->django views is added by default)
'websocket': AllowedHostsOriginValidator(
AuthMiddlewareStack(
URLRouter(
[
path('user-notification', ChatConsumer)
]
)
)
)
})
When i remove this line of code, runserver work: from messanger.contacts.consumers import ChatConsumer
But i don't understand what's wrong with my consumers file in contacts app:
from channels.consumer import AsyncConsumer
class ChatConsumer(AsyncConsumer):
async def websocket_connect(self, event):
await self.send({
"type": "websocket.accept",
})
async def websocket_receive(self, event):
await self.send({
"type": "websocket.send",
"text": event["text"],
})
In your settings.py file add:
ASGI_APPLICATION = 'yourappname.asgi.application'
I was able to solve this issue by going in the asgi.py file and import get_asgi_application() which act as tradition http request fallback Like so in asgi.py :
mport os
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator
from django.core.asgi import get_asgi_application
from django.urls import path
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
# Initialize Django ASGI application early to ensure the AppRegistry
# is populated before importing code that may import ORM models.
django_asgi_app = get_asgi_application()
from chat.consumers import AdminChatConsumer, PublicChatConsumer
application = ProtocolTypeRouter({
# Django's ASGI application to handle traditional HTTP requests
"http": django_asgi_app,
# WebSocket chat handler
"websocket": AllowedHostsOriginValidator(
AuthMiddlewareStack(
URLRouter([
path("chat/admin/", AdminChatConsumer.as_asgi()),
path("chat/", PublicChatConsumer.as_asgi()),
])
)
),
})
You need to add in your settings.py file :
ASGI_APPLICATION = 'yourappname.routing.application'
and that is because ASGI_APPLICATION is looking for application = ... in your files. And also there could be a potentional problem with your not adding ChatConsumer.as_asgi() in your path which will instantiate a new consumer instance for each connection.
I am hitting a conflict with a prior configuration and not sure how to get around the error.
error:
Exception Value: module 'userarea.views' has no attribute 'home_view'
from project urls.py:
$ cat exchange/urls.py
from django.contrib import admin
from django.urls import path, include
from pages.views import home_view, contact_view, about_view, user_view
#from products.views import product_detail_view
from userdash.views import userdash_detail_view, userdash_create_view
from django.conf.urls import include
from django.urls import path
from register import views as v
from pages import views
from userarea import views
urlpatterns = [
path('', views.home_view, name='home'),
path('', include("django.contrib.auth.urls")),
path('admin/', admin.site.urls),
path("register/", v.register, name="register"),
path('userdash/', userdash_detail_view),
path('contact/', contact_view),
path('', include("userarea.urls")),
path('create/', userdash_create_view),
path('about/', about_view),
path('user/', user_view),
]
I either get this error or problem with it trying to access my default.
But unable to find a work around.
from app views.py
$ cat userarea/views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def uindex(response):
return HttpResponse("<h1>New user dashboard area</h1>")
app urls.py:
$ cat userarea/urls.py
from django.urls import path
from . import views
urlpatterns = [
path("uindex/", views.uindex, name="user index"),
]
How do I get my new/2nd project to not conflict with my previous app and load it's own index page in it's directory?
full debug error:
AttributeError at /uindex
module 'userarea.views' has no attribute 'home_view'
Request Method: GET
Request URL: http://192.168.42.13:8080/uindex
Django Version: 2.2.7
Exception Type: AttributeError
Exception Value:
module 'userarea.views' has no attribute 'home_view'
Exception Location: ./exchange/urls.py in <module>, line 28
Python Executable: /usr/local/bin/uwsgi
Python Version: 3.7.3
Python Path:
['.',
'',
'/home/kermit/Env/secret/lib/python37.zip',
'/home/kermit/Env/secret/lib/python3.7',
'/home/kermit/Env/secret/lib/python3.7/lib-dynload',
'/usr/lib/python3.7',
'/home/kermit/Env/secret/lib/python3.7/site-packages']
Note updated urlpatterns twice and errors
new update:
This is what it appears to be calling, but I can't figure out how to differentiate between the two calls.
$ cat pages/views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home_view(request, *args, **kwargs):
return render(request, "home.html",{})
def contact_view(request, *args, **kwargs):
return render(request, "contact.html",{})
def about_view(*args, **kwargs):
return HttpResponse('<h1>About Page</h1>')
def user_view(request, *args, **kwargs):
my_context = {
"my_text": "This is my context",
"my_number": "123",
"my_list": [1121, 1212, 3423, "abc"]
}
print(args, kwargs)
print(request.user)
return render(request, "user.html", my_context)
Big UPDATE (changes made above also):
I create a brand spanking new project and used the exact same configuration and it works find.
(Env) piggy#tuna:~/www/src/exchange2 $ cat userdash/urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("userdash/", views.userdash, name="user dash"),
]
(Env) piggy#tuna:~/www/src/exchange2 $ cat exchange2/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("userdash.urls")),
]
(Env) piggy#tuna:~/www/src/exchange2 $ cat userdash/views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(response):
return HttpResponse("<h1>Hello World!</h1>")
def userdash(response):
return HttpResponse("<h1>User Dashboard!</h1>")
why does my include() method of creating directories want to conflict with a standard path()?
from
irc.freenode.net #django user <GinFuyou>
.
from userarea import views as userarea_views
the key was
userarea_views
i have installed django 1.10. And then ckeditor 5.0.3
When done with config i got an error "ImportError: No module named urls"
There is config settings.py:
INSTALLED_APPS = [
...
'ckeditor',
]
CKEDITOR_UPLOAD_PATH = 'upload/'
There is urls.py:
from django.conf.urls import url, include
(r'^ckeditor/', include('ckeditor.urls')),
There is urls.py of ckeditor_uploader:
from __future__ import absolute_import
import django
from django.conf.urls import url
from django.contrib.admin.views.decorators import staff_member_required
from django.views.decorators.cache import never_cache
from . import views
if django.VERSION >= (1, 8):
urlpatterns = [
url(r'^upload/',
staff_member_required(views.upload),
name='ckeditor_upload'),
url(r'^browse/', never_cache(staff_member_required(views.browse)),
name='ckeditor_browse'),
]
else:
from django.conf.urls import patterns
urlpatterns = patterns(
'',
url(r'^upload/', staff_member_required(views.upload),
name='ckeditor_upload'),
url(r'^browse/', never_cache(staff_member_required(views.browse)),
name='ckeditor_browse'),
)
Please any help!
WSGI_APPLICATION:
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "blago.settings")
application = get_wsgi_application()
Read the documentation
NOTICE: django-ckeditor 5 has backward incompatible code moves against 4.5.1.
File upload support have been moved to ckeditor_uploader. The urls are in ckeditor_uploader.urls while for file uploading widget you have to use RichTextUploadingField instead of RichTextField.
..
Add ckeditor_uploader to your INSTALLED_APPS setting.
...
Add CKEditor URL include to your project's urls.py file:
(r'^ckeditor/', include('ckeditor_uploader.urls')),
i've an issue with my code, may be one of you will be able to help me about this
here is my script.py :
#! /usr/bin/python
# -*- coding:utf-8 -*-
import jinja2.ext
import webbrowser
def main():
from flask import Flask, flash, redirect, render_template, \
request, url_for,escape, session
from flask_bootstrap import Bootstrap
app = Flask(__name__)
webbrowser.open_new_tab('http://127.0.0.1:5000')
Bootstrap(app)
#app.route('/')
def home():
return render_template('home.html')
#app.route('/choice')
def choice():
return render_template('Choice.html')
#app.route('/src&dest')
def GenerationPage():
return render_template('generate.html')
#app.route('/success')
def successfull():
return render_template('success.html')
return app.run(debug=True)
if __name__ == "__main__":
main()
and my setup.py :
import sys
import os
from cx_Freeze import setup,Executable
path = sys.path + ["src", "src/templates"]
includes = [sys, os]
excludes = []
packages = []
include_files = ['templates']
options = {"path": path,
"includes": includes,
"excludes": excludes,
"include_files": include_files
}
if sys.platform == "win32":
options["include_msvcr"] = True
base = None
if sys.platform == "win32":
base = "Win32GUI"
FirstTarget = Executable(
script="Other.py",
base=base,
compress=False,
copyDependentFiles=True,
appendScriptToExe=True,
appendScriptToLibrary=False
)
setup(
name="FlaskTrapeze",
version="0.1",
description="Ouvre une interface web",
author="Axel M",
options={"build_exe": options},
executables=[FirstTarget]
)
I'm facing this issue when I try to build it under windows
"AttributeError: 'module' object has no attribute 'rfind'"
Thanks for the help !