FlaskSocketIO retrieve list of all connected clients - flask-socketio

I am just beginning to learn Flask SocketIO.
The basic requirement is to gather all the client (along with info) that are connected to server. Below code is written to do just that.
Username is collected on click of a button.
#main.py
from flask import Flask, render_template, request, session, jsonify
from flask_socketio import SocketIO, emit, send
app = Flask(__name__)
socketio = SocketIO(app, manage_session=False)
clients = []
#socketio.on('client_connected', namespace='/connect')
def handle_client_connected_event(username, methods=['GET', 'POST']):
clients.append(
{
'client_session': request.sid,
'client_username': username,
'client_ip': request.access_route
}
)
print(clients)
#app.route('/')
def index(methods=['GET', 'POST']):
return render_template('index.html')
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0')
And Client side code:
//JS
var socket = io.connect('http://' + document.domain + ':' + location.port);
var socket_messages = io.connect('http://' + document.domain + ':' + location.port+'/connect');
$('#send_username').on('click', function(){
socket_messages.emit('client_connected', $('#username').val());
});
and lastly HTML
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script>
<script type="text/javascript" src="{{ url_for('static', filename='app.js') }}"></script>
<title>Document</title>
</head>
<body>
<input type="text", id="username">
<button id="send_username">Submit Username</button><br>
<!-- Connected User: -->
</body>
</html>
I am unable to get client info using this piece of code. Any insights as to where I may be going wrong?
Thanks for your help

Related

Error:createClient is not defined When using supabase cdn

I'm using Supabase CDN's for a project. When I call the createClient() function this error comes up:
createClient is not defined
I tried it with an older version of the CDN, with another browser and using the old method of SupabaseClient.createClient, but I got:
SupabaseClient is not defined
Is the CDN not working correctly or something else?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>HTML</title>
<!-- Custom Styles -->
<link rel="stylesheet" href="style.css">
</head>
<body>
<p>Nothing to see here...</p>
<!-- Project -->
<script src="https://cdn.jsdelivr.net/npm/#supabase/supabase-js#2"></script>
<script src="main.js"></script>
</body>
</html>
const SupabaseKey = // api here
const SupabaseUrl =// URL here
const options = {
db: {
schema: 'public',
},
auth: {
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: true
}
}
const supabase = createClient(SupabaseUrl, SupabaseKey, options)
I fixed it by adding an import statement in the JS file like this:
import createClient from 'https://cdn.jsdelivr.net/npm/#supabase/supabase-js/+esm'
The +esm at the end of the URL is from universal module and it now works.

Why opened page with AdminLTE looks broken?

I make site In laravel 9 with Inertiajs/vuejs 3 based on https://github.com/ColorlibHQ/AdminLTE 3 (dark mode).
I removed all jquery and use vuejs only. it works ok for for, but when I open site
is looks broken, like not all styles were loaded,
Please try enter to login into adminarea by url :
https://bi-currencies.my-demo-apps.tk/admin/currencies
credentials are in Login form
and pages looks like : https://prnt.sc/TCjBh0SefUMO 4
But if to refresh page with “CTRL+R” pages looks ok, in dark mode.
Any ideas why so and how that can be fixed?
More Details :
Adminare is based on https://github.com/ColorlibHQ/AdminLTE template(with "bootstrap": "^4.6.0").
Frontend is based on custom https://technext.github.io/space/v1.0.0/ template (with Bootstrap v5.0.1 )
I have the same design issue when I switch from admin area
frontend page https://bi-currencies.my-demo-apps.tk/home
I see this problem of other browsers of my Kubuntu 20 too.
Maybe problem is that that I use too different templates, but actually I use different layouts, so in
app/Http/Middleware/HandleInertiaRequests.php :
public function rootView(Request $request)
{
if ($request->segment(1) == 'user') {
return 'layouts/user';
}
if ($request->segment(1) == 'admin') {
return 'layouts/adminlte'; // TODO
}
return 'layouts/frontend'; // Current request is front-end
}
This project has no Redis or other chache tools installed. Sure I cleared all cache opening the site. Any other ideas?
Frontend template resources/views/layouts/frontend.blade.php :
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title inertia id="app_title">{{ config('app.name', 'Laravel') }}</title>
<link rel="shortcut icon" type="image/x-icon" href="/images/frontend_favicon.ico">
<link href="https://fonts.googleapis.com/css2?family=Yantramanav:wght#300;400;500;700;900&display=swap"
rel="stylesheet">
<!-- Styles -->
#routes
<!-- Scripts -->
<script src="//cdn.jsdelivr.net/npm/sweetalert2#11"></script>
<link rel="stylesheet" href="/css/theme.css">
<script src="/vendors/#popperjs/popper.min.js"></script>
<script src="/vendors/bootstrap/bootstrap.min.js"></script>
<script src="/vendors/is/is.min.js"></script>
<script src="https://polyfill.io/v3/polyfill.min.js?features=window.scroll"></script>
<script src="/vendors/fontawesome/all.min.js"></script>
<script src="{{ mix('js/app.js') }}" defer></script>
</head>
<body class="bg-light sidebar-mini layout-fixed layout-footer-fixed">
#inertia
</body>
</html>
and admin template resources/views/layouts/adminlte.blade.php :
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title inertia id="app_title">{{ config('app.name', 'Laravel') }}</title>
<!-- Google Font: Source Sans Pro -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">
<!-- Styles -->
<link rel="stylesheet" href="/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="/css/fontawesome_all.min.css">
<link rel="stylesheet" href="/css/adminlte.min.css">
<link rel="stylesheet" href="/css/admin_custom.css">
#routes
<!-- Scripts -->
<script src="//cdn.jsdelivr.net/npm/sweetalert2#11"></script>
<script src="/js/Chart.bundle.js"></script>
<script src="/js/OverlayScrollbars.min.js"></script>
<script src="{{ mix('js/app.js') }}" defer></script>
</head>
<body class="bg-light sidebar-mini layout-fixed layout-footer-fixed">
#inertia
</body>
</html>
1 common resources/js/app.js :
require('./bootstrap');
window.Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: false,
didOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
})
require('#fortawesome/fontawesome-free/js/all.min.js');
// Import modules...
import { createApp, h } from 'vue';
import { createInertiaApp, Link } from '#inertiajs/inertia-vue3';
import { InertiaProgress } from '#inertiajs/progress';
import mitt from 'mitt';
window.emitter = mitt();
const appName = window.document.getElementsByTagName('title')[0]?.innerText || 'Laravel';
import Multiselect from '#vueform/multiselect'
import VueUploadComponent from 'vue-upload-component'
import Paginate from "vuejs-paginate-next";
const app = createInertiaApp({
title: (title) => `${title} - ${appName}`,
resolve: (name) => require(`./Pages/${name}.vue`),
setup({ el, app, props, plugin }) {
return createApp({ render: () => h(app, props) })
.use(plugin)
.component('inertia-link', Link)
.component('Paginate', Paginate)
.component('file-upload', VueUploadComponent)
.mixin({ methods: { route } })
.component('multiselect', Multiselect)
.mount(el);
},
});
InertiaProgress.init({ color: '#4B5563' });
also in admin/settings page I added “Clear Cache” button, clicking on it next commands are run :
\Artisan::call('config:cache');
\Artisan::call('route:cache');
\Artisan::call('cache:clear');
\Artisan::call('route:cache');
\Artisan::call('route:clear');
\Artisan::call('view:clear');
\Artisan::call('clear-compiled');
but clearing cache did not help with this problem.
Can it be that reason of this problem that I have 1 common resources/js/app.js both for admin area and frontend part?
Thanks!
Once I was faced same problem with inertia and that works for me. Usually that happened when you used multiple-layouts, as well as those layout have different style-scripts.
Reason (problem):
As you have used one layout for frontend-pages (public pages) and other one for admin-pages.
So when user visited front-pages, all style scripts of frontend-layout loaded and it's work fine and looks good.
But, when user switched to admin-layout that's layout style-scripts not loaded. So, On hard-refresh (Crtl+R) that URL the appropriate layout style-scripts got loaded.
I read many article to switch layouts on run-time every article gives same solutions as you did in HandleInertiaRequests.php.
Solution:
Then I come to a point where I need to switch layout on clicking some link I did hard-loading as shown in below snippet instead of redirection by inertia-link:
<a :href="route('home')">
Home
</a>
By this way appropriate layout style-script got loaded.
My Assumption:
Moreover, I've seen your site-source-code (Ctrl+U) as shown in screenshot. You haven't loaded style-scripts by Laravel asset() helper method.
I suggest to try once by loading scripts & style link in blade file by Laravel standard approach (using asset() method) that might be a problem.
Attach CSS sheet
<link href="{{ asset('frontend/css/bootstrap.min.css') }}" rel="stylesheet">
Attach JavaScript/jQuery scripts
<script src="{{ asset('frontend/js/jquery-3.5.1.min.js') }}"></script>
After using asset() method, your links in site-source-code (Ctrl+U)
looks something like that:
Note:
make sure you must set appropriate APP_URL in .env file.

My css is not working in node.js Getting this error (ERROR IN DESCRIPTION) as it is too long

This is the error I am getting.
Refused to apply style from 'http://localhost:3000/public/stylesheets/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
This is my index.js file
//Requiring Dependencies
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const path = require('path');
//To run and parse EJS
const engine = require('ejs-mate');
//Using EJS-Mate
app.engine('ejs' , engine);
app.set('view engine' , 'ejs');
app.set('views' , path.join(__dirname, 'views'));
app.use(express.urlencoded({extended: true}));
//For use of files like js and css in public directory
app.use(express.static(path.join(__dirname, './public')))
app.get('/' , (req , res) => {
})
app.get('/home' , (req , res) => {
res.render('layouts/boilerplate')
})
This is the boilerplate.ejs where i want to add the stylesheet
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<base href="/">
<title>BoilerPlate</title>
<link rel="stylesheet" type="text/css" href="/public/stylesheets/style.css">
<!-- BOOTSTRAP CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
<!-- NAVBAR -->
<%- include('../partials/navbar.ejs') %>
<!--BOOTSTRAP Javascript-->
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.9.2/dist/umd/popper.min.js"
integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.min.js"
integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF"
crossorigin="anonymous"></script>
</body>
</html>
The bootstrap CSS however is working. So I tried removing the "rel" error goes but the stylesheet is not applied. I also tried to use the base method and still did not work, also added type=text/css, and still didn't work. Any idea why it is not working?

Empty body Using Prerender.io with Meteor

I try to use prerender.io with a Meteor 1.5 App. I use the npm prerender-node package
var prerenderio = Npm.require('prerender-node') .set('prerenderToken', token)
.set('protocol', protocol)
.set('host', host);
// Feed it to middleware! (app.use)
WebApp.connectHandlers.use(prerenderio);
I seed log in prerender.io with code 200. Paged are cached but pages only contain the head and an empty body.
To make tests, I added the package meteorhacks:inject-initial and inserted lines in the body and it works fine.
I wonder if I have a problem with the router that is flowrouter.
I also place
<head>
<meta charset="utf-8">
<meta name="fragment" content="!">
ALL <meta ... >
<!-- a script -->
<scripts ... >
<!-- prerenderio -->
<script> console.log(Date()); window.prerenderReady = false; </script>
</head>
To test, I flushed the cache of prerender.io.
when I test https://www.toto.com?_escaped_fragment_=
I don't have any time in the client console. I see the new line on prerender.io
I did the same test into
https://www.bing.com/webmaster/diagnostics/seo/analyzer
Now let's see the new cache line content:
Server: nginx/1.4.6 (Ubuntu)
Date: Wed, 21 Jun 2017 20:16:33 GMT
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: close
Vary: Accept-Encoding
Cache-Control: no-cache
Content-Encoding: gzip
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="/packages/meteorhacks_zones/assets/utils.js?1498075872540"></script>
<script type="text/javascript" src="/packages/meteorhacks_zones/assets/before.js?1498075872540"></script>
<script type="text/javascript" src="/packages/meteorhacks_zones/assets/zone.js?1498075872540"></script>
<script type="text/javascript" src="/packages/meteorhacks_zones/assets/tracer.js?1498075872540"></script>
<script type="text/javascript" src="/packages/meteorhacks_zones/assets/after.js?1498075872540"></script>
<script type="text/javascript" src="/packages/meteorhacks_zones/assets/reporters.js?1498075872540"></script>
<link rel="stylesheet" type="text/css" class="__meteor-css__" href="/f6675d95a01ce3ac63036505eb1ace94a68b1bb7.css?meteor_css_resource=true">
<meta charset="utf-8">
<title>Toto</title>
...
<meta name="robots" content="index, follow">
...
<!-- http referrer links -->
<meta name="referrer" content="always">
<meta name="fragment" content="!">
<!-- No resize on mobiles -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"> <!--320-->
<!-- a script -->
<script ... ></script>
<!-- prerenderio -->
<script> console.log(Date()); window.prerenderReady = false; </script>
</head>
<body>
<script type="text/javascript">__meteor_runtime_config__ = JSON.parse(decodeURIComponent("%7B%22meteorRelease%22%3A%22METEOR%401.5-beta.8%22%2C%22meteorEnv%22%3A%7B%22NODE_ENV%22%3A%22production%22%2C%22TEST_METADATA%22%3A%22%7B%7D%22%7D%2C%22PUBLIC_SETTINGS%22%3A%7B%22analyticsSettings%22%3A%7B%22autorun%22%3Afalse%2C%22Mixpanel%22%3A%7B%22token%22%3A%225fc6f49885cbf2ec8d80a15c0a310399%22%2C%22people%22%3Atrue%7D%2C%22Google%20Analytics%22%3A%7B%22trackingId%22%3A%22UA-60492530-2%22%7D%7D%2C%22ga%22%3A%7B%22account%22%3A%22UA-60492530-2%22%7D%7D%2C%22ROOT_URL%22%3A%22https%3A%2F%2Fwww.Toto.com%22%2C%22ROOT_URL_PATH_PREFIX%22%3A%22%22%2C%22appId%22%3A%221yyz6nr2dyysy1rxvng3%22%2C%22autoupdateVersion%22%3A%2237dc9ce25f5e0f5f3a2253bdcb3c80166a4e83d2%22%2C%22autoupdateVersionRefreshable%22%3A%2273bc2363ca210840ec3d6947a649e3388beca5c5%22%2C%22autoupdateVersionCordova%22%3A%224b9074136556412500d12284625a4f5d81ac3f3d%22%7D"));</script>
<script type="text/javascript" src="/fef4959b1bc37d5a9c2a1c09ddcb28fd7c374f10.js?meteor_js_resource=true"></script>
</body>
</html>
Here I gave the entire body content. I didn't remove any line.
Prerender user here. We had issues with Prerender not waiting until all scripts ran to completion and therefore the calculated dom is not yet fully rendered which sounds like what you're encountering. We solved this by using the prerender ready flag described in the prerender documentation copied here for convenience:
Put this in your HTML:
<script> window.prerenderReady = false; </script>
When we see window.prerenderReady set to false, we'll wait until it's set to true to save the HTML. Execute the following when your page will be ready (usually after ajax calls).
window.prerenderReady = true;

Location of jQuery script in HTML5 Boilerplate file?

Does H5BP assume that you will write your JavaScript and jQuery code so that it only executes when the window has fully loaded (using the onload listener)? The reason I ask is that H5BP locates the jQuery inclusion script tag at the bottom of the body tag as shown below. However, the script in which a cookie is being set will not work unless I move the jquery.min.js script element to the head element which precedes the body (and thus the execution of the cookie script). Thanks.
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<script src="js/vendor/modernizr-2.6.2.min.js"></script>
</head>
<body>
<p>This is HTML5 Boilerplate.</p>
<!-- Cookie isn't set when jquery.min.js follows this element block -->
<script>
var test_profile = { browserWidth: $(window).width() };
document.cookie = "test_profile=" + JSON.stringify(test_profile);
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.9.1.min.js"><\/script>')</script>
</body>
</html>
That first <script> block depends on jQuery ($(window).width()), so it cannot be used before jQuery has been loaded.
Just move that cookie script after the other two <script> blocks:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.9.1.min.js"><\/script>')</script>
<script>
var test_profile = { browserWidth: $(window).width() };
document.cookie = "test_profile=" + JSON.stringify(test_profile);
</script>

Resources