Django channels Websocket Disconnect - python-3.x

I want my Django app 'popinion1' to communicate via textmessage with a local machine.
pip freeze :
asgi-redis==1.4.3
asgiref==2.3.2
async-timeout==3.0.1
autobahn==18.12.1
channels==2.1.3
daphne==2.2.4
Django==2.1.3
redis==2.10.6
Twisted==18.9.0
When I do "manage.py runserver" there seems to be a connection or at least no errors
However as soon as I refresh the browser in terminal I get:
ERROR - ws_protocol - [Failure instance: Traceback: class'ValueError'>: No route found for path 'input/' [lots of lines]
ending with: WebSocket DISCONNECT /input/ [127.0.0.1:50506]
with "/input/" being my app.
Firefox inspector reports:
Firefox can't establish connection to Server with ws://127.0.0.1:8000
/input/ being my app.
my routing.py is
from django.conf.urls import url
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from channels.security.websocket import AllowedHostsOriginValidator, OriginValidator
from input.consumers import ChatConsumer
print('ChatConsumer: ', ChatConsumer.name)
application = ProtocolTypeRouter({
'websocket': AllowedHostsOriginValidator(
AuthMiddlewareStack(
URLRouter(
[
url(r'^input/(?P<username>[\w.#+-]+)/$', ChatConsumer),
]
)
)
)
})
the javascript in the html template:
<script>
console.log(window.location)
var loc = window.location
var wsStart = 'ws://'
if (loc.protocol == 'https:'){
wsStart = 'wss://'
}
var endpoint = wsStart + loc.host + loc.pathname
var socket = new WebSocket(endpoint)
socket.onmessage = function(e){
console.log("message", e)
}
socket.onopen= function(e){
console.log("open", e)
}
socket.onerror= function(e){
console.log("error", e)
}
socket.onclose= function(e){
console.log("close", e)
}
</script>
my consumers.py
import asyncio
import json
from django.contrib.auth import get_user_model
from channels.consumer import AsyncConsumer
from channels.db import database_sync_to_async
from .models import Thread, ChatMessage
from asgiref.sync import async_to_sync
class ChatConsumer(AsyncConsumer):
name = 'ChatConsumer'
async def websocket_connect(self, event):
print('connected! ', event)
await self.send({
"type": "websocket.accept"
})
async def websocket_receive(self, event):
print('receive! ', event)
async def websocket_disconnect(self, event):
print('disconnected! ', event)
CHANNEL_LAYERS in settings.py
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'asgi_redis.core.RedisChannelLayer',
'CONFIG': {
'hosts': [('localhost', 6379)],
},
#'ROUTING': 'popinion_project.routing.channel_routing',
}
}
so is it a wrong address in the routing.py? What's also weird is the last import of "ChatConsumer" in routing.py. It's "unresolved reference" but the print statement works.
print('ChatConsumer: ', ChatConsumer.name)
I'm following this tutorial
https://www.youtube.com/watch?v=RVH05S1qab8
I'd be happy to know how to get the websocket to connect. Hopefully provided all necessary information. Thanks in advance

The solution I used. It had something to do with the use of url.
from django.urls import re_path
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from channels.security.websocket import AllowedHostsOriginValidator, OriginValidator
from chat.consumers import ChatConsumer
application = ProtocolTypeRouter({
# Empty for now (http->django views is added by default)
'websocket': AllowedHostsOriginValidator(
AuthMiddlewareStack(
URLRouter(
[
re_path(r"^messages/(?P<username>[\w.#+-]+)", ChatConsumer),
]
)
)
)
})

Related

How to stop Django from hanging after page refresh using channels?

Using channels it connects properly when the page loads the first time but then hangs on refresh. Not sure why this is happening. I've placed the code below to see what might be happening?
# index.html
<script>
let socket = new WebSocket('ws://127.0.0.1:8001/ws/');
socket.onmessage = () => {
console.log("Connected");
};
socket.onclose = () => {
console.log('Websocket closed');
}
</script>
# app/consumer.py
from json import dumps
from time import sleep
from channels.generic.websocket import WebsocketConsumer
class WSConsumer(WebsocketConsumer):
def connect(self):
self.accept()
self.send(dumps({'message': 'connected'}))
for i in range(1000):
self.send(dumps({'message': i}))
sleep(2)
#app/routing.py
from django.urls import path
from app.consumers import WSConsumer
ws_urlpatterns = [
path('ws/', WSConsumer.as_asgi())
]
#core/asgi.py
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter
from channels.routing import URLRouter
from django.core.asgi import get_asgi_application
from app.routing import ws_urlpatterns
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings")
django.setup()
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(URLRouter(ws_urlpatterns)),
})
# core/urls.py
...
path('test/', views.IndexView.as_view()),
...
In my settings I've added channels just below the .sites app but above everything else and I've added the ASGI_APPLICATION and running the application with python manage.py runserver 127.0.0.1:8001

Scriptrunner/ Copying Project while logged-in as another user

I want to use my script, so that it will be executed by someone who is not me, but another user (ServiceUser) in the Jira Instance.
This is my functioning code, but I do not know how to make someone else execute it.
import com.atlassian.jira.project.Project
import com.atlassian.jira.project.ProjectManager
import com.atlassian.jira.project.AssigneeTypes
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.user.ApplicationUser
import com.atlassian.jira.component.ComponentAccessor
import com.onresolve.scriptrunner.canned.jira.admin.CopyProject
import org.apache.log4j.Logger
import com.atlassian.jira.bc.projectroles.ProjectRoleService
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.security.roles.ProjectRole
import com.atlassian.jira.util.SimpleErrorCollection
import com.atlassian.jira.security.roles.ProjectRoleManager
import com.atlassian.jira.project.ProjectManager
import com.atlassian.jira.project.Project
import com.atlassian.jira.security.roles.ProjectRoleActor
import com.atlassian.jira.bc.project.ProjectCreationData
import com.atlassian.jira.bc.project.ProjectService
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.project.AssigneeTypes
import com.atlassian.jira.project.type.ProjectTypeKey
// the key for the new project
def projectKey = "EXA987"
def projectName = "EXA987"
def log = Logger.getLogger("com.onresolve.jira.groovy.MyScript")
Thread executorThread = new Thread(new Runnable() {
void run() {
def copyProject = new CopyProject()
def inputs = [
(CopyProject.FIELD_SOURCE_PROJECT) : "SWTEMP",
(CopyProject.FIELD_TARGET_PROJECT) : projectKey,
(CopyProject.FIELD_TARGET_PROJECT_NAME) : projectName,
(CopyProject.FIELD_COPY_VERSIONS) : false,
(CopyProject.FIELD_COPY_COMPONENTS) : false,
(CopyProject.FIELD_COPY_ISSUES) : false,
(CopyProject.FIELD_COPY_DASH_AND_FILTERS) : false,
]
def errorCollection = copyProject.doValidate(inputs, false)
if(errorCollection.hasAnyErrors()) {
log.warn("Couldn't create project: $errorCollection")
}
else {
def util = ComponentAccessor.getUserUtil()
def adminsGroup = util.getGroupObject("jira-administrators")
assert adminsGroup // must have jira-administrators group defined
def admins = util.getAllUsersInGroups([adminsGroup])
assert admins // must have at least one admin
ComponentAccessor.getJiraAuthenticationContext().setLoggedInUser(util.getUserByName(admins.first().name))
copyProject.doScript(inputs)
}
}
})
executorThread.start()
I stumbled upon other codes, using things like
def oldLoggedInUser = jiraAuthenticationContext.getLoggedInUser()
jiraAuthenticationContext.setLoggedInUser(serviceUser)
jiraAuthenticationContext.setLoggedInUser(oldLoggedInUser)
but it was not succesful for me.
I have used following solution to change user during script execution:
def authContext = ComponentAccessor.getJiraAuthenticationContext();
def currentUser = authContext.getLoggedInUser();
def superuser=ComponentAccessor.getUserManager().getUserByKey("ANOTHER_USER_ACCOUNT")
authContext.setLoggedInUser(superuser);
// < do the needed work>
authContext.setLoggedInUser(currentUser);
I had first issues as my used another account had not needed Jira access rights (and I got funny "user must be logged in" errors)

reactjs - sidebar not working after store update

I am using reactjs.
node: version 14
I am developing on core-ui-react-template.
Sidebar did not work after updating the ./store file. I put the contents of the store file and index.js file below.
original website core.io
I have been working on it for a few days but I could not get any results. I couldn't find where was the mistake
index.js
import 'react-app-polyfill/ie11'; // For IE 11 support
import 'react-app-polyfill/stable';
import './polyfill'
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { icons } from './assets/icons'
import store from './store'
import { transitions, positions, Provider as AlertProvider } from 'react-alert'
import AlertTemplate from 'react-alert-template-basic'
import {Provider} from 'react-redux';
import ReactNotification from 'react-notifications-component';
import 'react-notifications-component/dist/theme.css'
React.icons = icons;
const options = {
position: positions.BOTTOM_RIGHT,
timeout: 5000,
offset: '1px',
transition: transitions.SCALE,
};
console.log(store.getState());
ReactDOM.render(
<Provider store={store}>
<AlertProvider template={AlertTemplate} {...options}>
<ReactNotification/>
<App/>
</AlertProvider>
</Provider>,
document.getElementById('root')
);
serviceWorker.unregister();
./store.js
import {applyMiddleware, combineReducers, compose, createStore} from "redux";
import customerReducer from "./components/helpers/reducers/customerReducer";
import userReducer from "./components/helpers/reducers/userReducer";
import appointmentsReducer from "./components/helpers/reducers/appointmenstReducer";
import thunk from "redux-thunk";
const initialState = {
sidebarShow: 'responsive'
};
const changeStateReducer = (state = initialState, { type, ...rest }) => {
switch (type) {
case 'set':
return {...state, ...rest };
default:
return state
}
};
const rootReducers = combineReducers({
customerInfo: customerReducer,
account_profile: userReducer,
appointmentsList: appointmentsReducer,
changeState: changeStateReducer
});
const allEnhancers = compose(
applyMiddleware(thunk)
);
const store = createStore(
rootReducers,
allEnhancers
);
export default store
As you know, I use core-ui-react template. There is a link below.
But after updating the ./store file, it shows "undefined" when I show it with console.log (sidebarShow) in "const sidebarShow = useSelector (state => state.sidebarShow)" line in TheHeader file.
https://github.com/coreui/coreui-free-react-admin-template/blob/master/src/containers/TheHeader.js
I think "useSelector (state => state.sidebarShow)" doesn't get the function here. It originates from here.
check out how combineReducers works: https://redux.js.org/api/combinereducers
your selector should be:
const sidebarShow = useSelector(state => state.changeState.sidebarShow)
you'll notice that changeState is not a very good key name, but that is another issue :)

How to store websockets at the server side with aiohttp?

I'm trying to make simple web-chat with rooms using aiohttp. Can you please advise me how to store my websockets connections? Some code below are simplified a bit. I'm getting an EOF error from socket time by time (and I can reproduce it), but i don't know why. So, i got a question, am i do it right? Should i close websockets everytime when i reload or follow to link? If not, so, how i will connect client with my already opened socket? Sorry for my eng ^^ thanks.
app.py
import asyncio
import aiohttp_jinja2
import jinja2
import hashlib
import collections
import os
from aiohttp_session import session_middleware
from aiohttp_session.cookie_storage import EncryptedCookieStorage
from aiohttp import web
from routes import routes
from middlewares import authorize
from motor import motor_asyncio as ma
from settings import *
basedir = os.path.dirname(os.path.realpath(__file__))
photo_dir = os.path.join(basedir, 'static/photo/')
async def on_shutdown(app):
for ws in app['websockets']:
await ws.close(code=1001, mesage='Server shutdown')
middle = [
session_middleware(EncryptedCookieStorage(hashlib.sha256(bytes(SECRET_KEY, 'utf-8')).digest())),
authorize
]
app = web.Application(middlewares=middle)
aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates'))
for route in routes:
app.router.add_route(*route[:3], name=route[3])
app['static_root_url'] = '/static'
app.router.add_static('/static', 'static', name='static')
app.client = ma.AsyncIOMotorClient(MONGO_HOST)
app.db = app.client[MONGO_DB_NAME]
app.on_cleanup.append(on_shutdown)
app['websockets'] = collections.defaultdict(list)
app['online'] = {}
app['photo_dir'] = photo_dir
web.run_app(app)
and websocket handler
class CompanyWebSocket(web.View):
async def get(self):
ws = web.WebSocketResponse()
await ws.prepare(self.request)
session = await get_session(self.request)
self_id = session.get('user')
login = session.get('login')
company_id = self.request.rel_url.query.get('company_id')
message = Message(self.request.app.db)
company = Company(self.request.app.db)
my_companys = await company.get_company_by_user(self_id)
for c in my_companys:
self.request.app['websockets'][str(c['_id'])].append(ws)
async for msg in ws:
if msg.type == WSMsgType.TEXT:
if msg.data == 'close':
await ws.close()
else:
await message.save_for_company({'data': 'data'})
mess = {
'data': 'data'
}
# send mess to users in company
for company_ws in self.request.app['websockets'][company_id]:
await company_ws.send_json(mess)
elif msg.type == WSMsgType.ERROR:
log.debug('ws connection closed with exception %s' % ws.exception())
try:
self.request.app['websockets'][company_id].remove(ws)
except:
pass
for _ws in self.request.app['websockets'][company_id]:
await _ws.send_json({'user': login, 'type': 'left'})
return ws

Connection request failed while connecting to sharepoint online

I am trying to connect sharepoint online i used the following code but the response it is showing is request failed . I tried the following code
#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.0-RC2' )
import groovyx.net.http.*;
import static groovyx.net.http.ContentType.*;
import static groovyx.net.http.Method.*;
import groovyx.net.http.HTTPBuilder;
import static groovyx.net.http.Method.GET;
import static groovyx.net.http.ContentType.TEXT;
import groovyx.net.http.RESTClient
import groovy.util.slurpersupport.GPathResult
import static groovyx.net.http.ContentType.URLENC
import groovyx.net.http.URIBuilder
def authSite = new HTTPBuilder( 'https://xyzsharepoint.com' );
authSite.auth.basic 'username', 'password';
authSite.request(GET) { req->
response.success = { resp->
println'request was successful'
assert resp.status<400
}
response.failure = { resp ->
println'request failed'
assert resp.status>=400
}
}
Suggest me where I went wrong.

Resources