#web-development

2 messages ยท Page 42 of 1

opal radish
#

Oh

#

lol

native tide
#

Lol

opal radish
#

it pinged the wrong person

#

i typed in floppy

native tide
#

Lel top kek

opal radish
#

@obtuse remnant

#

Thats better

#

Sorry for summoning you

native tide
#

'Summoning' ๐Ÿคฃ

opal radish
#

I have been reading this http://exploreflask.com/en/latest/organizing.html in an effort to clean up some of my code and have currently got it organised fairly similarly. I have two questions.

  1. How do I run the __init__.py package to run the app (as from what the article says I gather that you are meant to have the app = Flask(__name__) stuff in it.
  2. How could I import this app variable from the modules within the package so can access the app.config variable.

Here is how my __init__.py file looks

from flask import Flask
from flask_login import LoginManager

app = Flask(__name__)
app.config.from_pyfile("config.py")
tired root
bleak bobcat
silent girder
#

Do you use Django CMS?

tired root
#

@bleak bobcat The problem is, you cannot animate the drop

#

when you use <details>

bleak bobcat
#

True, and it's not even edge compatible anyway

tired root
#

According to caniuse it is

#

It uses chromium now

bleak bobcat
#

A made a pure css menu/page switcher using the checkbox trick a while ago, let me find it ^^

#

Oh, does it ? Good to know

tired root
#

Yeah, they rewrote Edge a while ago to use Chromium

bleak bobcat
#

I wasn't even aware, I didn't have a lot of time to spend on frontend recently ๐Ÿ˜ฆ

#

Oh, yea, not checkboxes, radio

#

But same principle

tired root
#

nice

#

but yeah, radios work better if you want only one open

#

could use that with a accordion too

bleak bobcat
#

I wonder about the accessibiltiy of using this

#

Wouldn't it be confusing ?

tired root
#

I would animate the transition to make the change more apparent

#

but I dont think there are any issues with it

bleak bobcat
#

Yea I'm not gonna use it, I just dropped it on my github a few months ago for anyone who wants to use it ^^'

#

I need to start using text browser to check for accessibility, might be weird for a blind person for example to hear there's a radio buton there

native tide
#

What are my options for implementing paypal checkout , visa , and so on like is there any platform that has all those options implemented

#

i know about that mollie.com or something they have a few

vagrant adder
#

Shopify?

#

Or stripe

candid owl
#

i have a problem with my urls

#
from django.contrib import admin
from django.urls import path, include, url

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^accounts/', include('accounts.urls'))
]
#

its not finding my page that code is from my urls file in accounts

bleak bobcat
#

This looks like the old python 2 way of doing urls. Can you try changing it to and report back ? :
path('accounts/', include('accounts.urls'))

tired root
#

@native tide BMT micro is established and a long time in the market

#

Bought quite a few games over it

#

They can also handle downloads shall you need it

candid owl
#

File "C:\Users\andrewstyler\Documents\VENV\my_django_project\accounts\urls.py", line 1, in <module>
from django.conf.urls import path
ImportError: cannot import name 'path' from 'django.conf.urls' (C:\Users\andrewstyler\Documents\lib\site-packages\django\conf\urls_init_.py)

#

now im getting this error for some reason

#

when i try to runserver

#

nvm i got that fixed

#

seems to work now thanks

shadow orchid
#

hello

vagrant adder
#

hello daggy

shadow orchid
#

i want to pass a string how do I

#

@vagrant adder

vagrant adder
#

string of what kind

#

as an argument or in body

tired root
#

I just want to leave this here: https://rsms.me/raster/ Very useful grid tool, without having to download megabytes of bootstrap. I โ™ฅ๏ธ it

#

it's from one of the founders of Spotify

shadow orchid
#

@vagrant adder its a webservice which uses xml SOAP, i want to pass in a string so I can get the outputed yoda talk so its an arg

vagrant adder
#

i have no idea, never consumed any xml api

shadow orchid
#

damn it

tired root
#

@shadow orchid You need to look at their documentation

#

Generall API's like that work by querying urls with the information

shadow orchid
#

i do not understand

tired root
#

and that works both ways

shadow orchid
#

beginner

tired root
#

You are on the right track, but you need to figure out how to do a yoda talk request. We won't be doing that for you.

#

We cannot learn all APIs out there

shadow orchid
#

any documentation i can read about xml

#

just to get me started

tired root
#

This has nothing to do with xml per se

#

It is more about how to form the URL to make them accept the data

#

and what headers to send

#

HTTP headers

shadow orchid
#

OMG thanks

#

http

native tide
#

I'm not sure if there is or isn't going to be more to learn inside the Django framework alone than there is inside everything Ive learned about python elsewise so far.

shadow orchid
#
import requests
url = ' http://www.yodaspeak.co.uk/webservice/yodatalk'
headers = {
  'use': 'literal',
  'namespace':'http://www.yodaspeak.co.uk/webservice/yodatalk',
  'encodingStyle':'rpc',
  'message': 'yodaTalkRequest',
  'inputText':'My name is Arnav'

}

response = requests.request("GET", url, headers=headers)```
#

@tired root

#

i just get the help site

#

sorry error 404

#

i fixed it

#
import requests
url = ' http://www.yodaspeak.co.uk/webservice/yodatalk'
uri = 'http://www.yodaspeak.co.uk/webservice/yodatalk'
message = 'yodaTalkRequest'
xsd = "MY NAME IS ARNAV"
inputText = xsd
headers = {
  'use': 'literal',
  'namespace':uri,
  'encodingStyle':message,
  'parts':inputText}

response = requests.request("GET", url, headers=headers)

print(response.text)



#

still error 404

#

@tired root

native tide
#

I would like help getting gunicorn to serve static files on Django server as per this question.

I'm not interested whatsoever in any shortcut way this is done on a local development server.

I want to know how its done in production. No one seems to want to answer that question.

#

I'm going to show you my config on my nginx server. One moment.

#

I believe I may have found the reason why due to a bad path in my config. Excuse this question.

jaunty quiver
#

@native tide 404 could also be static files not being found. I personally dont use uwsgi but rather gunicorn and nginx but in my experience 404 errors are either caused by a requested file not being found (this might be a missing staticfile etc) or urls/views being misconfigured. What I am noticing, that I do different is that I Include a urls file from the app, instead of defining the urls for the apps in the main urls file. Mostly to keep it separated and more easily readable.
Also I personally recommend https://docs.djangoproject.com/en/3.0/topics/http/urls/#naming-url-patterns naming your url patterns.
The Last thing that might be causing this is your view that the url points to being misconfigured, as those can 404 too if they either return None/Null or dont exits or return an actual 404

#

looking at urls would be the first thing I would do after looking whether or not the staticfiles are getting delivered correctly

jaunty quiver
#

Does django-model-utils support Django 3.0+?
The wiki https://django-model-utils.readthedocs.io/en/latest/index.html doesnt mention django-model-utils supports Django 1.8 through 2.1 (latest bugfix release in each series only) on Python 2.7, 3.4, 3.5 and 3.6. it;
But the repository DOES mention it: https://github.com/jazzband/django-model-utils
django-model-utils supports Django 2.1+ and 3.0+. This app is available on PyPI.

glacial sable
#

i really need some help with flask
my home page has a container with 3 columns

#

im using wtforms to fill in a form on the right column

#

it then displays the info filled in on the left column

#

my problem is that

#

if im using long words or a string without spaces

#

the line goes into the other columns

#

and i dont want that to happen

#

if the string is very long without spaces then it goes across the screen and moves the rest of the ui

#

can anyone solve my issue or at least guide me in the right direction?

native tide
stiff totem
#

hi, i am using qrcode to generate QR image. Now i need to pass this image with some link as response in django. i tried HttpResponse but i can not figure it out how to pass qr image without saving this in folder. right now i am passing only image like following.

 ...
 qr = qrcode.make(res["response"]["qr_string"])
 applink = res["response"]["qr_link"]
 response = HttpResponse(content_type="image/png")
 qr.save(response, "PNG")
 return response
quasi ridge
#

I would think you'd want to create an HTML response, and build the HTML to include the image in an <a> element, with the URL as an href attribute

native tide
#

Speaking of that, can you just do something like

# Django Imports
from pathlib import Path

content = Path("index.html")

def index(request):
  return HttpResponse(content.read_text())
#

I just started this. It seems like a nasty way to fit HTML into a function

#

otherwise

native tide
#

oh cool, I guess I just havent gotten this far yet

#

I have however already had an opportunity to play with Jinja2 templates as a result of static page generators.

#

Its roughly the same right?

#

with Django that is

#

yeah it appears that way

#

One thing that is going to be really new for me is passing variables through urls...

stiff totem
#

@bleak bobcat yeah but it's CBV- DetailView, and i wanted to pass in context as image but qrcode.make returns PIL image object.

#

Thing is i can not pass this until i save it and return it's path

bleak bobcat
#

I was talking to TLS ^^'

stiff totem
#

Oh my bad.

bleak bobcat
#

Do you want your view to return an image or html with an image tag ?

stiff totem
#

@bleak bobcat not an image. Image must have some link alongside with it. So i am passing context on DetailView

bleak bobcat
#

So like offby1 said, return html with a <a> tag containing an <img> tag ^^

stiff totem
#

@bleak bobcat i changed it to this. But context['qr'] is not an image

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["qr"] = qrcode.make(context.get("object").response.get("response").get("qr_string"))
        context["link"] = context.get("object").response.get("response").get("qr_link")
        return context

#

i tried return html with <img /> with src but this qr.make does not returning image

normal blade
#

I was recently trying to figure out Django. I don't understand the function of models.py.. can someone help?

sharp briar
#

where is this file?

normal blade
#

so, i created a new app in the vm, it is in that new app

#

basically i went to the project directory in pipenv, started the vm by writing pipenv shell and then created an app using python manage.py startapp

sharp briar
#

right so you don't understand models @normal blade?

normal blade
#

yep

sharp briar
#

It's basically an ORM

#

Just classes that represent data in your database

#

make storage of data super easy

normal blade
#

does models link it with sqlite?

normal blade
#

okay thanks ๐Ÿ™‚

sharp briar
#

and going through them all, they're quite helpful

normal blade
#

Cool!

sharp briar
#

but it's basically a python interface to interact easily with whatever database engine you use

#

you'll understand after a few tutorial pages

normal blade
#

gotcha!

vagrant adder
#

@normal blade models are a chain between python code and your database

#

it writes raw sql queries and fetches given data back to you

normal blade
#

hmm

#

so, do models define what type of data can go into an sql query?

vagrant adder
#

yes

#

database columns and column types

normal blade
#

if i want to compare something basic like a todo-list and something like discord for example

#

if i replicate more of the models i wrote for a todo-list, can i get something like discord

vagrant adder
#

probably yes

#

discord has very complex database architecture but you can try to mimic it

normal blade
#

okay..

#

so i was following this tutorial by CSDojo for making a startup using python and js

#

and for the todo app, he wrote this in the models.py file

#

class TodoItem(models.Model):
content = models.TextField()

vagrant adder
#

so TodoItem is an object with content attribute

#

and it gets content value from a database

normal blade
#

this basically says that create a sql datable where text can be added and removed eh?

#

oh gotcha

#

so for eg, i wanted to mimic something like the online and offline component of discord

#

will something like that when combined with views.py to add the name when a request is sent and delete that exact name when person is offline (request stops) work? (in a very basic sense of-course) @vagrant adder

vagrant adder
#

yes, it will work

#

it's up to you to set up the logic behind the view, but that's th concept

normal blade
#

okay perf thanks!

shadow orchid
#

hello

#
   <soapenv:Header/>
   <soapenv:Body>
      <yod:yodaTalk>
         <inputText>I am Daggy</inputText>
      </yod:yodaTalk>
   </soapenv:Body>
</soapenv:Envelope>```
#

i have this request

#

I want to use this in python

#

to get the content

#

please help me

bleak bobcat
native tide
#

so i have this code

#
$(document).scroll(function () {
    var y = $(this).scrollTop();
    if (y > 800) {
        $('.navigation').fadeIn();
    } else {
        $('.navigation').fadeOut();
    }
});```
#

but i only want it to work when it is home.html

#

when i go to the other webpages the navigation bar should be there already

#

i am no javascript expert so i am asking here

#

someone can show me how here faster

#

OOF!!

#

nevermind

#

i put the script to that js file in the layout dot html

#

instead of home dot html

#

๐Ÿ˜…

#

oh

#

i am still in need of help

#

when on home.html: css display:none;

#

when on store.html:css display:block;

#

i think that needs to happen in the JS file

native tide
#

i actually want the navigation bar to be a whole different style when it is not on the home page

keen bone
#

Hey guys, I need to make a website for a school project, and want to impress my teacher for a better grade

#

How do I start off with web development?

dense slate
#

Django Q: If I have a manytomany field of the user model that is basically a list of games (so people can just check off games they play), what would be the best way to allow for choosing the level of experience with each game (i.e., low, medium, high)?

dense slate
#

Would a through model be used here?

#

With the the through model having a choicefield?

vagrant adder
#

@keen bone i would suggest taking a look at corey's schafers youtube tutorial series

bleak bobcat
#

Sounds good Damian, yea, that's what through model are made for

ornate hull
#

Struggling abit. Trying to trigger a modal jquery after 5 seconds. It works, but the contents of the box show on the bottom left of the page until it triggers. Code:

<script> setTimeout(function(){ $( function() { $( "#dialog-confirm" ).dialog({ resizable: false, height: "auto", width: 400, modal: true, buttons: { "Delete all items": function() { $( this ).dialog( "close" ); }, Cancel: function() { $( this ).dialog( "close" ); } } }); } ); },5000) // 5 seconds. </script>

And then in the html:

<div id="dialog-confirm" title="Empty the recycle bin?"> <p><span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 20px 0;"></span>These items will be permanently deleted and cannot be recovered. Are you sure?</p> </div>

#

I get that the div at the bottom shows up because it's in the HTML, but how do I hide it until it's needed?

ornate hull
#

๐Ÿค” Thanks for the quick reply @bleak bobcat. But the contents are still showing, even before the dialog opens.

bleak bobcat
#

You need to initialize the dialog with that option on page load (not after 5sec), and then after 5sec you call the open method

ornate hull
#

Well damn, it worked. I feel dumb now lol, thank you @bleak bobcat

restive kindle
#

Hi, I need some suggestions on a javascript based diagram library for complex searching of databases. So the user can design their diagram and can be presented as a form. Eg. Forename / Surname has an input.

ornate hull
#

Oh god. Have you considered using SQL to help keep the databases ?

restive kindle
#

hah I do use sql on the backend its just its scale and relations make it hard for basic forms to implement

ornate hull
#

I see. Well I'm not sure I'm much help, my javascript and SQL knowledge is awful at best.

restive kindle
#

๐Ÿ™‚

ornate hull
#

But I boiled open all 9 of my mozzarella sticks looking for similar projects I did with bottle (found none), so something has to go well for you. Good luck! ๐Ÿ˜‚

restive kindle
#

hahha thanks, im close

obtuse leaf
#

hey guys, so i spent all day trying to get apache2 to work with my django app, but i keep getting a 500 internal server error. I've tried different tutorials and have seem to gotten them to work, but whenever I modify the .conf files to my own application, it just doesnt work. Can anyone help and see if im missing anything?

#

if i just run my application via python3 manage.py runserver 0.0.0.0:5000 it works fine as well

restive kindle
#

checked /var/log/apache2/error.log?

obtuse leaf
#

Thanks, this gives me an idea of whats going on.
o my error is:
python home /usr/bin/python3 is not a directory

#

or actually it's just giving me

#
[Fri Feb 21 04:17:17.212556 2020] [core:notice] [pid 16601:tid 140530834226112] AH00094: Command line: '/usr/sbin/apache2'
[Fri Feb 21 04:17:26.886630 2020] [mpm_event:notice] [pid 16601:tid 140530834226112] AH00493: SIGUSR1 received.  Doing graceful restart
[Fri Feb 21 04:17:26.986492 2020] [mpm_event:notice] [pid 16601:tid 140530834226112] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured -- resuming normal operations
[Fri Feb 21 04:17:26.986522 2020] [core:notice] [pid 16601:tid 140530834226112] AH00094: Command line: '/usr/sbin/apache2'
restive kindle
#

Its because 'home' cannot be found because of the working directory of which python is operating. So if python is started /home/user, /home/user/home doesnt exist so. You need to specify the absolute path home (i presume /home)

fathom bronze
#

Hi guys, Have any of you used Odoo/OpenERP or ERPNext?

wise yacht
#

Hey Guys, I am in the process of developing a webapp to control some stuff through a raspberry pi and I am trying to figure out how some people have the "#" symbol at the end of their pages instead of the actual url? I am using flask and have a bootstrap template

bleak bobcat
vestal hound
#

are you talking about fragment identifiers?

tired root
#

@wise yacht Apache/Nginx rewrite rules

#

Take a gander at mod_rewrite and the corresponding htaccess rules

wise yacht
#

@tired root I will look at Apache/Nginx rewrite rules

#

@vestal hound Hi to be honest im not sure.

native tide
#

hi

#

im getting this error

native tide
#

im using latest django, and python 3.8.1

tired root
#

You need to import from the six package, not django.utils @native tide

#

django.six.whatever

#

Or at least something you have installed is trying to do that

#

I'd say jet is the evil bastard

native tide
#

xd yes

tired root
#

xd yes?

native tide
#

yes. but that's weird

limber laurel
#

Can anyone help me with an issue regarding flask here?

zealous siren
#

!ask

lavish prismBOT
#
ask

Asking good questions will yield a much higher chance of a quick response:

โ€ข Don't ask to ask your question, just go ahead and tell us your problem.
โ€ข Don't ask if anyone is knowledgeable in some area, filtering serves no purpose.
โ€ข Try to solve the problem on your own first, we're not going to write code for you.
โ€ข Show us the code you've tried and any errors or unexpected results it's giving.
โ€ข Be patient while we're helping you.

You can find a much more detailed explanation on our website.

limber laurel
#

Oh sorry, I guess I wilk just get to the point, so I seperated my routes from the run file, and when I dont import a route I get a 404 error, but if I import 1, all of them work.
Why does this work for all routes

from routes import register

If __name__ == '__main__'
    app.run()

And this doesnt for none of the routes


if __name__ == '__main__'
    app.run()

#

Also can anyone help me understand what I should need to have imported to my run file?

polar nova
#

@native tide if you use more stable version 3.5 it may be ok

novel mantle
#

can any1 take a look at my little newbie flask project? i'm stuck for few hours trying to find out why my reset_password_email gives me invalid or expired token

haughty saffron
#

Is there a website that displays a good contrasting colour to a provided one?

quiet mirage
haughty saffron
#

thanks

opal bramble
wicked basalt
#

Hi, I'm using Selenium to try to check if a text is on my page by using :

    print("EXIST ON PAGE SOURCE")
else :
    print("NOT EXISTING")```
My "text_to_be_found" is dynamic: it will appear only after I select an element in a dropdown list (it is not on the page if I refresh the page).  However, the code doesn't detect this dynamic text. How can I do that?
white pewter
#

anyone i need help

marsh canyon
#

its jpeg

#

look closely

white pewter
#

oh got it

marsh ginkgo
#

Anyone has experience to setup Django with Apache2?

bleak bobcat
#

!ask

lavish prismBOT
#
ask

Asking good questions will yield a much higher chance of a quick response:

โ€ข Don't ask to ask your question, just go ahead and tell us your problem.
โ€ข Don't ask if anyone is knowledgeable in some area, filtering serves no purpose.
โ€ข Try to solve the problem on your own first, we're not going to write code for you.
โ€ข Show us the code you've tried and any errors or unexpected results it's giving.
โ€ข Be patient while we're helping you.

You can find a much more detailed explanation on our website.

marsh ginkgo
#

I get "No module named site" while trying to configure Apache2 with Django. Worth mentioning that I have my Django files in /home/ which Apache2 might not like? But I remember reading that we should not use Django in /var/www/ as with PHP... My logs is located here: https://stackoverflow.com/questions/60352670/apache2-no-module-named-site-with-wsgi-py

#

I have searched everywhere for an answer, thinking of perhaps run everything outside nenv and in /var/www. But the Django documentation didn't recommend that... So confusing

tired root
#

is your wsgiScriptAlias correctly set?

#

The only point where the apache config differs from a html host are 2 lines

#
 WSGIDaemonProcess scriptname.wsgi user=wsgi group=wsgi threads=1
        WSGIScriptAlias / /path/to/python/script```
#

@marsh ginkgo

marsh ginkgo
#

I'll take a look, I just scrubbed the VPS ๐Ÿ™‚ Will skip using nenv and try do everything correctly from the start (had different packages installed etc etc)

tired root
#

user may differ for you

marsh ginkgo
#

Thx

native tide
#

Hey guys,

just a quick question - I am dealing with my first server and currently focusing on security. Lets encrypt cert. present, nginx configured to always redirect to https.

Question - is there any need for port Nginx HTTP to be open? These are my ports:

OpenSSH ALLOW Anywhere
Nginx HTTP ALLOW Anywhere
Nginx Full ALLOW Anywhere
5432/tcp ALLOW Anywhere

and since everything is going through HTTPS, I thought to close HTTP & FULL and just open Nginx HTTPS?

Does this make sense?

quasi ridge
#

well, if you want to redirect http requests to https, you need the http port open

#

also congratulations; most people don't bother to secure their web servers

native tide
#

@quasi ridge thanks! I just got my first paying customer and the server must run smooth - that's why I bother haha

Besides above, I have SSH keys in place, TLS Encryption for outgoing emails... I won't bother with isolation my Db.

Is there anything I might have missed?

quasi ridge
#

hell I dunno

#

security is hard

#

if I were charging customers to run a web site for them, I'd offload as much as possible to competent third party: amazon, google, azure, heroku, &c

#

squarespace

crude jungle
#

How can i learn internet protocols

#

?

muted zealot
#

when using AJAX and Flask. If I want to send two separate types of post data with two different purposes based on the button pressed on the webpage. Can I just use the .ajax{ data: } to pass a string variable into flask and use a IF statement to decide which method to run?

native tide
#

@muted zealot based on the button pressed? Wrap the button around a form, give each a value and in Flask just make an if and compare it to the button value

muted zealot
#

@native tide this works even if my URL will all direct to the home root?

native tide
#

sure - why not?

Please give me a proper example of what you want to achieve

muted zealot
#
            $.ajax({
                data : { userIdInput : $('#userIdBox').val(), buttonSelected: 'searchPlayer'},
                type : 'POST',
                url : '/'
            })

this is my ajax data for the submit button. This button will perform a search for a user.

if the user has an account more than 365 days old a second button appears. This button will add that player to the leaderboard which is on the home page.

            $.ajax({
                data : { buttonSelected: 'appendPlayer' },
                type : 'POST',
                url : '/'
            })

then I have

@app.route('/', methods=['GET', 'POST'])
def process():
    if request.method == 'POST':
      if request.form['buttonSelected'] == 'searchPlayer':
shadow orchid
#

@tired root i did it

#

i figured out about SOAP and xml

#

i fugured out the intricacies of the request lib

#

i now can do it

muted zealot
#

actually. I don't think I should be using ajax for this. Going to turn to javascript and mysql

tired root
#

@shadow orchid nice.

wild thunder
#

hey guys, someone could clear some topics for me? i'm not finding info about (idk how to search for it)

#

it's on django

#

let's supose i have an app

#

it will have models

#

these models can be acessed for all the apps

#

or just the app it's inside?

opal vale
#

Guys, I have the following problem:
I'm creating bot to my favourite game. It works like that, everything in one session:

one account have several characters, so now you have to choose which one to play,
 then it starts fighting(fight requests),
 healing itself if it gets low health in fight response
it goes until it reaches error or "logged out" in response, so pretty much FOREVER
*between every request there is 500ms sleep.```
its very simple program. I would like to turn this to webpage to allow other people use my bot as the following:
```user passes login and password to game, 
bot log in to account (start session)
my server returns to user list of available characters
user chooses character to play
bot starts playing and in every fight it updates user's page (allows user to see if bot is working)```
And I have written something in flask, but i got stuck: I can not make my program support more than 5 users (with threading module)
is it possible to do with asynchronous or something? How can I do that?
I just ask for small hints or suggestions, everything would be nice

tl;dr
How to run multiple infinite functions that are sending requests with sleeps between requests and are updating user's page in every request done?
quasi ridge
#

sounds like:

#

one thread per request

#

have each thread put its results onto a thread-safe queue that all threads share

#

have another thread, perhaps your web server's main thread, pull from the queue and send a message via websockets to the browser

opal vale
#

I have tried spawning new thread for every new user, but it goes up to 5, and then crashes (5 users maximum, that is not so much :D)

#

if I didn't ask well enough there is simplified question:
how can I have multiple "http sessions" running in parallel in one python script with async? (i need really a lot sessions, like 100-200)

tired root
#

Use a web server

#

don't use python for that

#

Apache, nginX can each hold a lot of connections.

opal vale
#

Eeeem, its kind of complicated to explain, but I need to have many session BETWEEN MY SERVER AND GAME SERVER
and thats the problem ๐Ÿ˜„

tired root
#

but those aren't http sessions, are they?

#

is it a web game?

opal vale
#

yep

#

they are http sessions

tired root
#

Then you can still use a web server

#

use flask running on apache and your issue should be gone

#

it's all just web requests

opal vale
#

Lets say I want to do the following function (oversimplified):

def funccc(parameters):
  while True:
    post(link1)
    sleep(1)
    post(link2)
    sleep(2)
    post(link3)

how am I able to handle, lets say 100 simultaneous functions like that?

tired root
#

spawn threads

opal vale
#

threads have limits

#

with 2 physical threads, if im correct, i can get up to 5 functions running

tired root
#

Python can spawn 255 threads

#

if your computer will be able to handle it is another question, depending how heavy the computing load is

opal vale
#

how are sleeps done?

#

if I spawn 100 threads with 100 sleeps, is it "counting time" on every thread?

tired root
#

every thread needs to call time.sleep(x) in his own context to yield the remainder of it's quantum to another thred

opal vale
#

I still dont understand, I was not able to run more than 5 functions (on one-core-cpu), however, cpu usage was ~1%

quasi ridge
#

maybe paste a very simple (i.e, no more than 20 lines) program that reproduces the problem

#

I'd think you could have hundreds of threads, particularly if they spend most of their time sleeping

lavish sinew
#

Hello, I am running this jquery statement. It doesn't throw out any errors and doesn't do anything when I run it. When it run the same statement in the chrome console, it works without issue. Any ideas why its not working?

var statesDropdown = $('#statesDropdown');

// some lines down in a function...
statesDropdown.css('display', 'none');
#

Im using this inside a Flask project btw

rigid laurel
#

Probably due to when you are running the code. I cant quite remember, but you should have that wrapped inside a jquery document.onLoad equivalent

distant bobcat
#

Anyone have a good recommendation for a Flask tutorial?

vagrant adder
#

@lavish sinew all jquery you do needs to be wrapped around $(document).ready();

$(document).ready(function(){
  $("p").click(function(){
    $(this).hide();
  });
});

so function that is being passed as an argument to $(document).ready(); is what you are writing to manipulate DOM

limber laurel
#

For admin interfaces, should I better make mh own solutions without any plugins or use something like flask_admin?

native tide
#

@limber laurel dude i was about to ask same thing hahah

#

I just used flask admin and so far the customization and making your "own" unique looking dashboard would be fairly tasking but i dont have clue it just looks like that...

#

Making something with flask_roles seems kinda easier for me to understand...

tired root
#

I've programmed an admin panel, solely with flask_login

#

that one is useful, otherwise you'd have to program the sessions yourself, which isn't that simple

native tide
#

Can i consider myself a web developer if i just copy paste code and than launch that website to a server?

#

For example: When i don't know how to style a nav with css and just copy paste a good looking nav from someone else.

#

75% of the css file consist of copy pasted code.

quasi ridge
#

if you get it working, then ... maybe

#

you're judged on your results, not how well you understand what you're doing. It's just that, if you don't understand what you're doing, it's extraordinarily unlikely that you'll get good results.

native tide
#

For example: when i copy paste code but i don't even understand it?

#

It worries me sometimes .hehe

quasi ridge
#

it should

tacit current
#

What would be a good api to scrape weather information from a website?

#

other than bs4

rigid laurel
#

Why would you scrape that?

tacit current
#

to make an app, to show the weather

#

open source ofc

quasi ridge
#

@tacit current darksky has a proper API; it's not hard to use

rigid laurel
#

Practically no websites will allow you to scrape like that, and this server can't help with something that breaks tos

quasi ridge
#

no scraping needed

tacit current
#

OH.

rigid laurel
#

Openweatherapi is very easy to use

tacit current
#

i wasen't sure if web scraping was the only option

#

i see

#

i'll use the api

worn tangle
#

i need some help on how i can integrate flask-socketio into an existing flask app thats ran by doing python -m flaskapp but i cant figure out how to do it

native tide
#

Hey, do we have api experts?

#

So I have an identification server and an api that i want to access using the id server's tokens

#

is it a good idea to cache users and their access tokens on the api's servers?

#

so after this initial authentication, I don't have to rely on spamming the auth server anymore

jaunty quiver
#

so I am using django with docker and my staticfiles are missing in my container but the admin files are there??

#
STATIC_URL = "/staticfiles/"
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "staticfiles")
]
#

my staticfile settings in my settings.py

limber laurel
#

Can I initialize Flask_Login in my config.py file?

vagrant adder
#

you certainly can but config.py is commonly used for specifying app configuration, not instancing other flask extensions

limber laurel
#

Ok, I get an error that says filter_by() takes 1 argument byt 2 were given

#
user = User.query.filter_by(form.email.data).first()
#

Nvm

#

Forgot email=

bold mortar
#

Hi

#

i have MultiValueDictKeyError Issue when use POST method

#

how can i fix that?

bleak bobcat
#

Did you do something like request.POST['some_key'] @bold mortar ?

#

You need to do request.POST.get('some_key', some_dafault_value)

bold mortar
#

i checked that too

bleak bobcat
#

Then code + stacktrace pls

bold mortar
#

but didnt save

#

it save False as value

#

?

elder nebula
#

Have anyone used ckeditor_uploader for django CMS here?

haughty saffron
#

Ive got this HTML snippet i need to use in every html file, but its becoming a task to manually copy+paste changes.
Is there anyway i can get this header into every file (without an iframe)?

    <header id="menubar" style="max-width: 99%;font-family: Arial;border-radius: 8px;border: 3px solid black;width:100%;background-color: #40ed9c;padding: 4px 8px">
        Welcome to <span class="link" onclick='r("/r/join.html")' style="color: #ae0052">TBIH's</span> Website!
        <button class="menubutton" style="float:right" onclick="r()"><i class="fas fa-home"></i> Home</button>
        <button class="menubutton" style="float:right" onclick='r("/contact.html")'><i class="fas fa-file"></i> Contact <i class="fas fa-plus"></i> resources</button>
        <button class="menubutton" style="float:right" onclick='r("/partners.html")'><i class="fas fa-file"></i> Partners</button>
        <button class="menubutton" style="float:right" onclick='r("discord/index.html")'><i class="fas fa-folder"></i> discord</button>
    </header>
tired root
#

Are you using jinja?

#

@haughty saffron

#

Normally one is using templates for stuff like that

#

in jinja for example: {% include('yourfile.j2') %}

haughty saffron
#

ok

#

well i got a new issue with text wraps

#
    <div>
      <h1 id="top" style="font-family:Arial">TBIC Discord page</h1>
      <iframe style="vertical-align: top"src="https://ptb.discordapp.com/widget?id=[redacted]&theme=dark" width="350" height="500" allowtransparency="true" frameborder="0">Your browser doesn't support iframes!</iframe>
      <span class="text" style="align: top;overflow-wrap: normal;font-family:Roboto">Our entire group is centered around our discord server. It's where we spend most of our time.
    </div>
#

i need the text to align next to the iframe, but can't get the wrap to work

tired root
#

use grids

haughty saffron
#

thanks

tired root
#

Bascially, create one column on the side, spanning from top to bottom

#

the other column is the rest of the page

#

if you need finer grained control, create 10 columns, give 2 to discord and span 8 for the rest

#

@haughty saffron This is an example from my project. As you can see multiple columns and the sidebar spans over 2

haughty saffron
#

ohk ty

bold citrus
#

hi, so i'm using discord oauth on my site, the issue i'm having is basically when a new user logs in with discord oauth, it creates a database entry for them as well as a stripe customer, but some customers have been reloading the page and this has caused duplicated customers to be generated, what's the best way to stop this?

#
def create_user():

    user_request = get_user_info(session['access_token'])
    user = user_request.json()
    if user_request.status_code == 401:
        return redirect(url_for('logout'))

    guilds_request = get_user_guilds(session['access_token'])
    guilds = guilds_request.json()
    if guilds_request.status_code == 401:
        return redirect(url_for('logout'))
    
    # culogging
    print(f"==========CREATING NEW USER {user['username'] + '#' + user['discriminator']}==========")
    response = stripe.Customer.create(
        name=user['id'],
        description=user['username'] + '#' + user['discriminator'],
        email=user['email']
    )
    
    culogging = mongo.db.users.insert_one({
        'user': user['username'] + '#' + user['discriminator'],
        'avatar': user['avatar'],
        'discord_id': session['discord_id'],
        'customer_id': response['id'],
        'email': user['email'],
        'admin': False,
        'orders':[],
        'guilds': guilds
    })

    print("==========CULOGGING1==========")
    print(str(culogging))
    
    culogging2 = mongo.db.users.find_one({'discord_id': session['discord_id']})
    print("==========CULOGGING2==========")
    print(str(culogging2))

    return culogging2
#

my create user method

restive kindle
#

Is this function being called every request? There is no function to check whether the user already exists.

bold citrus
#

@restive kindle no, there is a check to see if the user exists, then this function is called, though i figured out the problem

#

2nd question

#

ok so i have built this ecommerce platform with flask for a product i'm selling, it uses the stripe charges API and delivers a digital product, the issue i'm having tho is my site at one point received a ton of traffic at the same time and i oversold stock because there were so many concurrent charge requests that were processing. i was wondering what the most effective way to control stock was so that i don't oversell. i tried doing it where the moment someone clicks purchase, stock is remove and then if their card declines or there is an error, it will add back the stock that was removed but was wondering if there is a more effective method for doing this

bold citrus
#

anything like that except for flask?

vagrant adder
#

Flask limiter

#

@bold citrus

restive kindle
#

I think he means creating flow/queue rather than concurrent requests.

vagrant adder
#

Task queue?

restive kindle
#

I think you would have to implement something like this outside of flask.

vagrant adder
#

Yeah, i can't find anything that limits rate based on queue

restive kindle
#

There is a library called Redis Queue. Id do it like this; display as if everything in the transaction went fine, add to queue. Upon full transaction then to tell the user something went wrong. I think amazon kind of does this but based upon where the product is in it's production/distribution.

vagrant adder
#

Redis queue can be used for this but i didin't mention it because it's main purpose is to handle background tasks

#

You can certainly do it with redis but that would be overengineering

restive kindle
#

Im not exactly a python programmer as such so you are probably right. A fifo queue should be simple to implement tho

vagrant adder
#

This article implements waiting queue

tired root
#

Can someone here tell me how to use the application context in flask correctly? Because I dont get it.

#

In my frontend.py:

# Get new app from flask
frontend = Flask(__name__)
executor = Executor(frontend)

with frontend.app_context():
    g._executor = executor```
#

In updateflow.py:

from flask import g, current_app
from flask_executor import Executor

with current_app.app_context():
    executor = g.get("_executor", None)


def update_character(token: dbTokens):
    with current_app.app_context():
        executor.submit(update_character_worker, token)```
#

That is where I run into issues with the infamous app context message

#

@patent cobalt Sorry for the ping, but can you help here?

#

I've got it working so far by using

def update_character(token: dbTokens):
    with current_app.app_context():
        print("Update")
        executor = g.get("_executor", None)
        executor.submit(update_character_worker, token)```
#

Actually does not work, g returns None. but the context message is gone.

patent cobalt
#

I have not done a lot with flak myself, I'll ask around in our helpers channel if someone's available that has

#

Okay, I've been looking into the docs, but this hooks into the flask application-flow for a request and I don't have a lot of experience with that, since I never used flask. (I don't work as a dev and I've mainly used Django for personal projects.) You could try the Pallets server (Pallets is the project behind flask); I suspect that they'll see why immediately: https://discord.gg/t6rrQZH

tired root
#

Alright, thanks

patent cobalt
#

Did you check whether or not "_executor" attribute exists and is assigned to None or that g.get returns None?

#

With g objects, you should be able to check that using attribute in g

tired root
#

I am assigning it now in a special function: python @frontend.before_request def before_request(): g.executor = executor

#

so, this should be available, but get returns None

#

A quick test says it's not in g

#
        if not "executor" in g:
            print("Not there")```
amber harbor
#

hello.. i have a question about my front-end code sending requests to my backend restful api.. should it be on the client or the server?

native tide
amber harbor
#

self.project.title

#

just do BaseModel.project.title i guess

native tide
#

then I get AttributeError: 'ForwardManyToOneDescriptor' object has no attribute 'title'

patent cobalt
#

The reason self is not defined is because you're defining a class attribute, not working within a method

#

In this case, you want to base the upload directory based on the value of another field (title), right?

#

The easiest way to do that is to create a callabe (probably a function) that does it for you

#

something like:

def get_upload_location(instance, filename):
    return f"{instance.path.to.attribute}/blog/{filename}"


class MyModel(models.model):
    img = models.ImageField(upload_to=get_upload_location)
#

The callable will be passed a reference to the instance you're creating (so you can access the title field) and the original filename. As it looks like you're not changing that, I've included it as is in your thing.

#

You may want to use pathlib or a better path-joining method instead, but this is just a basic example

#

(The reason you cannot do this directly in the ImageField definition is that this upload location needs to be determined for each instance you create and the expression for the class attribute is only evaluated once)

native tide
#

@patent cobalt thanks for this great answer!

#

I found that this solution is even in django docs

native tide
#

sorry, forgot 'self'

patent cobalt
#

You can, but you need to pass a callable as the argument to that ImageField upload_to parameter

#

So, your DRY function needs to be a factory instead of something like that

#

(You can also use functools.partial/functoolspartialmethod as the factory)

#

Something like this (but you seem to prefer a java-esque class-based style):

def get_upload_location(dir):
    def inner(instance, filename):
        return f"{instance.path.to.attribute}/{dir}/{filename}"
    return inner

class MyModel(models.model):
    img = models.ImageField(upload_to=get_upload_location(dir='blog'))
#

Another option is by using partial/partialmethod as the factory for these callables

native tide
#

it looks like a decorator ?

#

this solution is really simple, thanks once again ๐Ÿ™‚

native tide
#

Could not find function %s in %s.\n' % (self.value.__name__, module_name) ValueError: Could not find function inner in pages.models.

#

I tried your solution but probably missing something

patent cobalt
#

it looks like a decorator ?

It does, yeah. It's based on the principle: The outer function creates a new function object and returns that so we can use it. It's a "function factory". The difference with a decorator is that the outer function takes the function we're decorating as an argument and (usually) does something with that old function (like calling it from the new function object).

#

Could not find function %s in %s.\n' % (self.value.__name__, module_name) ValueError: Could not find function inner in pages.models.

How did you use my code? The inner name should only be used within the "factory function", not outside of it

wise yacht
#

Hi guys, I am using flask to create a web app and am trying to have some check boxes that will modify what nav items are visible. I am able to create the checkboxes but I cannot get them to keep the value of checked or unchecked and I am not sure how to use it to modify what tabs are visible

#

here is a snippet of my code <div class="form-check"> <label class="form-check-label"> <input class="form-check-input" type="checkbox" value="" checked=""> Configuration Page </label> </div> </fieldset> <button type="submit" class="btn btn-primary">Update</button>

gleaming stag
#

Hi. Flask noob here. I'm wondering how to handle an oauth session in a flask app. How can I keep track of a session's tokens? If I use a class that handles authentication, token refreshing, and HTTP methods, where do I instantiate it so that it persists across my flask views? Thank you.

gleaming stag
#

erm -- looks like Authlib is the way to go. i'll post again if i run into issues. thank you

rustic pebble
#

Hey I am looking to implement recaptcha on my website. Can someone with a response captcha bypass mine?

#

I mean people who have used captcha services to acquire captcha keys

limber laurel
#

So I want to query my table objects from my database to a htmk template, how can I do something like that?

#

Like querying a database but to a html file

vagrant adder
#

you can't query from html

limber laurel
#

How can I display my table members then for example all the users, do I need to set them in a didt and do it that way ir can I do it directly?

vagrant adder
#

are you using flask or django

bold mortar
#

hi

#

def adTodo(request):
c = request.POST['content']
new_item = TodoItem(content=c)
new_item.save()
return HttpResponseRedirect('')

#

here i am getting MultiValueDictKeyError

#

i changed code

#

def adTodo(request):
c = request.POST.get['content',False]
new_item = TodoItem(content=c)
new_item.save()
return HttpResponseRedirect('')

#

like this

#

but here i am getting TypeError at /addTodo/

#

how can i fix that?

cobalt ruin
#

hi, can someone help me understand how the picture tag works

#
<!DOCTYPE html> 
<html>
    <head>
        <meta charset="utf-8">
        <title>kitty</title>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <picture>
            <source media="(max-width: 480px)" srcset="images/dog.jpg">
            <source media="(max-width: 600px)" srcset="images/snake.jpg">
            <source media="(min-width: 900px)" srcset="images/kittyface.jpg">
            <img src="images/kittyhalf.jpg" alt="fallback">
        </picture>
    </body>
</html>

im not understanding how the min/max-width works

real wraith
#

Min-width shows the picture if the viewport (browser)'s width is less than the set value I think.

#

Sorry, min width is if the browser is wider than it says*

cobalt ruin
#

thats what i thought, but for example, this snippet

<picture>
    <source media="(min-width: 480px)" srcset="images/dog.jpg">
    <source media="(min-width: 600px)" srcset="images/snake.jpg">
    <source media="(min-width: 900px)" srcset="images/kittyface.jpg">
    <img src="images/kittyhalf.jpg" alt="fallback">
</picture>

always shows my dog image. Shouldnt it show my kittyhalf image when lower than 480px, my dog pic when at 480-599px, my snake pic when at 600px-899px, and my kittyface whenever the browser is bigger than 900px?

real wraith
#

Have you tried changing the order, they might be blocking?

cobalt ruin
#

i tried, but i just confused myself more

real wraith
#

Ah, try changing to max-width, as it wont display if the browser's viewport is too small

cobalt ruin
#

how can i have chrome show me the size of itself?

real wraith
#

I believe its ctrl shift m for firefox, then select responsive and you can set the size

cobalt ruin
#
<source media="(max-width: 480px)" srcset="images/dog.jpg">
<source media="(max-width: 600px)" srcset="images/snake.jpg">
<source media="(max-width: 900px)" srcset="images/kittyface.jpg">
<img src="images/kittyhalf.jpg" alt="fallback">

ok i changed to max width like you said, but it still doesnt make sense in the order of how the pix show

#

when i have the browser be its lowest width, i get my snake pic, if i make it slightly bigger, i get the kittyface pic, and the next pic that shows is the fallback

#

now the dog never shows up

#

oh

#

i just used firefox

#

instead of chrome, and now my dog shows up

#

hmmm

real wraith
#

Odd, had you reloaded the page?

cobalt ruin
#

well no, its just that ive been using chrome to test the tag

#

and when you mentioned fire fox uses the crt shift m, it didnt work on chrome, so i ran the html with fire fox instead of chrome

#

for some reason fire fox's width can go lower than chromes

real wraith
#

Ok, just as a note, the w3schools uses min width in a descending order.

<picture>
  <source media="(min-width: 650px)" srcset="img_pink_flowers.jpg">
  <source media="(min-width: 465px)" srcset="img_white_flower.jpg">
  <img src="img_orange_flowers.jpg" alt="Flowers" style="width:auto;">
</picture>
cobalt ruin
#

ok thanks

#

so how does that affect whether i use min or max

#

should there only ever be one max?

#

one min?

real wraith
#

So, max us easier to understand when you are looking back weeks/months later, as it is readable

#

And makes some sense

cobalt ruin
#

so i should only use max?

real wraith
#

You probably could, as you have a fallback image.

cobalt ruin
#

does the source tag have a height attribute?

#

or size?

#

I mean, i want to be able to set the images i use to 300, 400, 500px respectively

#

i dont see it in w3

real wraith
#

<source src=... alt=... style="height: 300px;">

#

I think...

cobalt ruin
#

oh, right, css

real wraith
#

Yeah

#

Are you trying to avoid it?

cobalt ruin
#

im actually trying to avoid the style=

#

my prof said its bad practice, and its best to use a css file to style my html

real wraith
#

Ok, so the css for something like this would look like this:

picture source {
    height: 300px;
}
cobalt ruin
#

but how would that allow my 2nd and 3rd options be 400px and 500px respectively

real wraith
#

Add separate classes to each picture, like breakpoint1 and breakpoint2 or dynamically change the size using css media queries

#

So this

<picture>
  <source media="(min-width: 650px)" srcset="img_pink_flowers.jpg">
  <source media="(min-width: 465px)" srcset="img_white_flower.jpg">
  <img src="img_orange_flowers.jpg" alt="Flowers" style="width:auto;">
</picture>

Would become

<picture>
  <source media="(min-width: 650px)" srcset="img_pink_flowers.jpg" class="break1">
  <source media="(min-width: 465px)" srcset="img_white_flower.jpg" class="break2">
  <img src="img_orange_flowers.jpg" alt="Flowers" class="break3">
</picture>

With the css

.breakpoint1 {
    height: 300px;
}
...etc
#

Alternatively, you could use css media queries. Which would eliminate the need for separate classes

cobalt ruin
#

that didnt work

#

the images stayed the same size throughout

real wraith
#

An example of a media query would be:

@media only screen and (max-width: 600px)ย {
ย  picture source {
   height: 300px;
ย ย }
}
cobalt ruin
#

well not the same size as each other, but the same size they were already

real wraith
#

Try adding display: flex; to the style

#

Also, firefox highlights errors in your html by grating them out, you can usually hover over them to see the issue

#

In the ctrl shift i menu

cobalt ruin
#

adding flex just doesnt show anything at all

#

pure white

real wraith
#

Ah

#

Uhh

#

Here's a list of ways you can try to display it

#

Yeah, flex is wrong lol

#

Sorry, I would test but I'm on my phone so it's very hard to type out code and test it

cobalt ruin
#

appreciate the help

real wraith
#

Is it working?

cobalt ruin
#

not the 300px, 400px, 500px stuff, but i believe i understand the picture tag better now

#

i shouldve been using fire fox

#

ยฏ_(ใƒ„)_/ยฏ

real wraith
#

Ok, it's a bit odd that only firefox worked

#

If you want, send me your html and css and I'll try to help

cobalt ruin
#
<!DOCTYPE html> 
<html>
    <head>
        <meta charset="utf-8">
        <title>kitty</title>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <picture>
            <source media="(max-width: 480px)" srcset="images/dog.jpg" class="break1">
            <source media="(max-width: 600px)" srcset="images/snake.jpg" class="break2">
            <source media="(max-width: 900px)" srcset="images/kittyface.jpg" class="break3">
            <img src="images/kittyhalf.jpg" alt="fallback">
        </picture>
    </body>
</html>
.break1
{
    height: 300px;
}
.break2 
{
    height: 500px;
}
.break3
{
    height: 700px;
}
#

i widened the gap for the height in case the difference wasnt big enough to notice, but its still not working

#

so 300, 500, 700 instead of 300, 400, 500

real wraith
#

You don't appear to be closing your source tags with </source>

#

Which means you are nesting them

#

Same with img

cobalt ruin
#

thats how they're supposed to be ?

#
<picture>
  <source media="(min-width: 650px)" srcset="img_pink_flowers.jpg">
  <source media="(min-width: 465px)" srcset="img_white_flower.jpg">
  <img src="img_orange_flowers.jpg" alt="Flowers" style="width:auto;">
</picture>
#

w3 doesnt close em either

real wraith
#

Oh, sorry, I'm not familiar with the picture tag

#

Try adding

picture {
  display: block;
}
#

If you want, in like an hour or so I can rely to make one for you

cobalt ruin
#

ok sorry, no, she meant to edit it in photoshop and have that be the 300, 400, 500px

#

so, yeah, this works now thanks

real wraith
#

ok

#

Just as a note, scss make this whole idea easier, as it uses "Mixins", which mix into the code.
EG:

@mixin for-phone-only {
    @media (max-width: 599px) {
        @content;
    }
}

img {
    @include for-phone-only {
        height: 500px;
    }
}

Which, when compiled, becomes

@media (max-width: 599px) {
  img {
    height: 100px;
  }
}
cobalt ruin
#

thanks for the reference

limber orchid
#

I'm using django and my model has a field

tags = ListCharField(base_field=models.CharField(max_length=30), max_length=300)

I would like to be able to run a query that gives me all posts where the list contains a certain string

#

I've tried

MyModel.objects.get('MyTag' in tags)

but it gives me an error saying tags is not defined

#

what's the correct argument to return the set?

bold citrus
#

so i need a way to make my endpoint only do one user's request at a time, i'm making a payment processor and the issue i'm having is stock numbers are being unaccurately changed, probably due to multiple people purchasing at the same time, anyway i can make it where one persone purchases after another, i tried redis queue but it was brining up a lot of errors

#

anyother options?

#

no payment processor, it's an online store

restive kindle
#

import threading
import queue

# Functions to be performed on each
# item in the queue
def work(n):
    # n = some arg
    print(n)

# Function to be performed on each thread
# q = the queue
def worker(q):
    while True:
        item = q.get()

        if item is None:
            break

        work(item)
        q.task_done()

q = queue.Queue()
threads = [] # running threads
number_of_theads = 1 # allowed number of threads
for i in range(number_of_theads):
    # t = threading.Thread(target=worker, args={"q": q})
    thread = threading.Thread(target=worker, args=[q])
    thread.start()
    threads.append(thread)

# add items to queue
for item in [1,2,3]:
    q.put(item)

# go through queue until completed
q.join()

# Can add items after the fact (eg. flask route)
q.put(4)
q.put(5)
q.put(6)

# To stop workers
# for i in range(number_of_theads):
#     q.put(None)
#
# for t in threads:
#     t.join()


#

python queue library

bold citrus
#

oh wow

#

ty

#

let me try this

limber laurel
#

@vagrant adder About the querying that I asked about yesterday, I am using flask.

native tide
#

that is the django.urls.reverse() function

restive kindle
#

the top answer explains

native tide
#

Thank you. I figured that the docs were making it clear in some way I should see rather than just search for it. I'll keep that in mind next time it stumps me.

#

comment from that stackoverflow post

">>>but what if you want to change the url in future", These kinds of subtleties that are useful on .0001% of the time and the solution is shipped like a useful feature, and people use it as if they are 'best practices' and leave the mess. TBH if when one changes the urls in future you just do a global find-replace. Even this solution(use url_name) is prone to the problem of 'what if you want to change the url_name in future?' Been coding in Django for over 5 years and yet to meet the need for url_reverse. The best way to deal with these kinds of oddities is to refuse to use them. โ€“ nehemiah Nov 13 '17 at 4:49
#

I think that guy might have a point.

restive kindle
#

true

native tide
#

How did you use my code? The inner name should only be used within the "factory function", not outside of it
@patent cobalt Same as you. It's working now. Don't know what was the problem yesterday ๐Ÿ™‚ Thanks for help!

native tide
#

Is there any default way to get specify object in template instead of doing something like this with everyone: image_1 = Images.objects.get(id=1) ? Maybe I can add custom filter ? In other words: can I use in template new object created via django admin without adding it to views ?

limber laurel
#

Is that a good idea to mix for example wtforms with just regular custom forms?

manic ravine
#
from flask import Flask,render_template, request
app = Flask(__name__)
@app.route("/", methods=["GET", "POST"])
def home():
    if request.method == "POST":
        url = request.form["url"]
        print(url)
    return render_template('index.html')

if __name__ == "__main__":
    app.run()```
#

index.html```html
<!doctype html>
<html>
<head>
<title>test</title>
</head>
<body>

    <form method="POST" action="">
        <input type="text" name="url">
        <input type="submit" value="Send">
    </form>
    </body>
</html>```
#

Bad Request
The browser (or proxy) sent a request that this server could not understand.

#

any help

vagrant adder
#

You gotta set action

#

For which route is it posting

fresh dock
#

@manic ravine form action="/"

vagrant adder
#

action={{ url_for('home') }}

#

url_for('home') will return what you set as @app.route() argument

#

In this case just "/"

fresh dock
#

Otherwise flask doesn't know what to do with it

#

And kicks back a 400 bad request

hasty gulch
#

So, this may be a dumb (flask) question but I have an app that is starting to get quite a few routes added. It seems like I can start organizing the routes into modules using blueprints. I can create and register the blueprints and the new routes work but I'm a little lost on how to make the database models available to each view module. I feel like I might be able to reinitialize the flask app and DB in the views folder __init__.py file but that seems wrong. Is there a widely-accepted way this should be done? I'm not a pro by any means so forgive me if this is a dumb or poorly worded question.

limber orbit
#

Hey all, I just built my first flask app but I now have to package it up in a neat bow. I'm looking to see if any of you have good resources that I could read on A: how do I check if the database doesnt exist and create it at run time B: how to create a setup page that can write a config for the app. So if I set this up the first time I get something the makes me create first user, lets me upload web certificates and then creates the db and app ready.

#

If this is the wrong room please let me know ๐Ÿ˜„

vagrant adder
#
.
โ”œโ”€โ”€ app
โ”‚ย ย  โ”œโ”€โ”€ __init__.py
โ”‚ย ย  โ”œโ”€โ”€ models.py
โ”‚ย ย  โ”œโ”€โ”€ config.py
โ”‚ย ย  โ”œโ”€โ”€ errors
โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ __init__.py
โ”‚ย ย  โ”‚ย ย  โ””โ”€โ”€ handlers.py
โ”‚ย ย  โ””โ”€โ”€ some_blueprint
โ”‚ย ย      โ”œโ”€โ”€ __init__.py
โ”‚ย ย      โ””โ”€โ”€ routes.py
โ”œโ”€โ”€ requirements.txt
โ””โ”€โ”€ run.py
#

and in blueprints you can import models by from app.models import SomeModel

hasty gulch
#

Thank you. I think I've created some kind of circular import issue but I think I'm closer.

limber orbit
#

implement an api key for your app

hasty gulch
#

the key (in theory) is only known / accessible by the user that generated it or that it was generated for

zealous siren
#

yep

hasty gulch
#

don't give your competitors accounts to your application

#

then yeah, not much you can do

#

unless you know exactly who each of your users are

tired root
#

@still palm Do the request on your own server

#

Don't do it via javascript, do it via Python requests

#

Those run on your server, not in the browser

clear kayak
#

So right now Iโ€™ve got an ajax form that does post requests to a django view, which in turn does authenticated put requests to my hue lights.

If I want those puts to be done periodically in the background, would it be crazy/dumb to just do a timed loop in my front end to make post requests? Is there a better way to do this asynchronously (for a private site)?

tired root
#

@still palm You have to send it one way or the other. But slice the data, only send one page, send the others later

#

Don't just dump everything

#

Use caching and minify and gzip your html

#

@clear kayak I have done something similar for rest requests for a project

#

Not, it is no crazy

#

Just make the thread sleep for xx seconds before the next

#
def update_worker():
    while True:
        requests.get(f"http://[{backend_ip}]:{backend_port}/")
        time.sleep(120)
clear kayak
#

Sweet thanks. Seemed like the most straightforward solution

native tide
#

where do you think django.db.models.F class gets its single character name from? Just to sort of help me remember where it is and why its called that.

#

a model field, I suppose.

#

Pretty much the entire experience of learning Django is

#

"This thing we just showed you is so common that we've made something to streamline it."

#

And then you go a little further until you get to, "That entire thing you just learned can be streamlined like this."

restive kindle
#

create a new class and inherit the user class and edit the functions

restive kindle
#
from django.contrib.auth.models import User

class CustomUser(User):
    def __init__():
        super().__init__()
#

you would then have to edit it from there, im not one for django

native tide
#

Do you prefer Flask if not Django?

#

I sort of just picked one. But I feel like eventually I'd like to have a look at Flask. For now Im going to just learn Django

#

It seemed like they were saying if what I was creating was fairly... standard... that Flask could be easier. Like for instance a microblog would be easier to put together in Flask was the example someone gave. But apparently that if I was trying to build something that had never been built before, Django would allow me to do that.

#

Is that accurate or bad generalization?

#

Frankly, the major take away from everything Ive done in Django tutorials so far is, "I still need a front end solution for any of this to be received well."

#

I know HTML, CSS, and am familiar with bootstrap.

#

But my JS is awful.

#

I was hoping that by getting into this I would not need as much of it

#

But there are a few more interactive ideas I have that will mean I eventually need to just buckle down and practice it.

#

Whats a good JS framework for mixing with server side python frameworks?

mild path
#

So.. i decided to mess around with python and some website / app development stuff. I was just curious as to what people think i should search for in regards to tutorials / courses. My main goal right now is i am developing a backend with python, Did a bunch today with YAML and now im stuck at what to use that would work really well to tie it all together as an interface.. The site/app will be customized a ton, kind of a ecommerce / gaming type of site. I was looking at bootstrap or MDB bootstrap.. ?? any suggestions what would help me get a nice UI setup that would integrate with my python work.??? Would like it , if possible, to be something that has a bunch of drag and drop type layout that i can tie to my APi

restive kindle
#

So you want a 'framework' to develop a UI or a website design

mild path
#

yes if thats the terminiology.. im basically a day into learning so im still trying to figure out how things are fully tied together and work together.

#

right now im just using a wireframe program to basically lay out my ideas but i would like to start laying them out much more professional looking

restive kindle
#

for website designs you can use psdfreebies but read the license before using

#

web frameworks can be angular.js, vue.js, react.js

mild path
#

yea i was just researching those 3 to see what would be the better way to go for my goal

#

ill have to dig a little deeper

clever sparrow
#

I'm not sure if this is right Channel for this Question, but I wonder what is most valuable info I can get about website. I am creating toolbox on rpi3 and the first tool takes wbisite link as an input and as output I want some valuable info which be later saved for data science proste.

rigid laurel
#

Its pretty hard to figure out what is/isn't valuable without a specific goal in mind

restive kindle
#

Whois history im sure is a premium feature so maybe just catalog whois data for sites

clever sparrow
#

@Charlie It's project to train Python so all kind of info which is worth saving

restive kindle
#

Train python? A NN?

rigid laurel
#

what do you mean by train python?

#

Its much easier to have an idea of what your goal is before starting the project

#

for example, you could track things like load times, accessibility features. You could track things like whois data as has been suggested. You could extract text content of divs for NLP sutff, you could save images to do some weird CV thing with

#

but thats going to be a lot of wasted effort

#

unless you have an idea of what you want to do going into it

clever sparrow
#

@Ccb14 I'm sorry I meant to train programming in Python not NN

restive kindle
#

yeah, do what charlie suggested

clever sparrow
#

@Charlie Thats a Long-term project to train different areas but mostku data scrapping and ML

#

*in diffrent areas

native tide
#

๐Ÿ˜ฉ why does most flask tutorials not use app factory pattern? Even worse, some of them write all in one file

clever sparrow
#

@Charlie Ill propably go for it, thanks for advice pydistrong

vagrant adder
#

@native tide that's probably because most of the developers who write tutorials don't use it often so they are not aware of it

native tide
#

Yea maybe

fiery tapir
#

Iโ€™m in the midst of learning python as my first language and one of my main projects Iโ€™ll be building with a friend is a fantasy esports website for league of legends that my entire friend group will privately use for awhile.

#

I was wondering after doing some research and reading what would be the best web platform for python to use for this. Django or flask?

#

Basically itโ€™ll consist of pro players getting points based off of in game stats pulled from the riot games api. A draft phase to choose the players on your team, scheduling players to play against each other every week for the duration of the games season

restive kindle
#

It doesnt seem large / complex enough to justify for django's extras. I would recommend flask however some will disagree. I recommend reading some articles before making a decision.

fiery tapir
#

Alright shall do and thank you!

#

The most complicated part I see for this would be the draft phase and also maybe adding in a way to change the leagues settings if we want to change how many points are given for a specific stat

#

We do plan on opening it to the public too way later on

slow thorn
#
[2020-02-27 18:10:00,860] ERROR in app: Exception on /oauth_callback [GET]
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/flask/app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/flask/app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/flask/app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/flask/app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/flask/app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "discord_oauth_login_server.py", line 48, in oauth_callback
    discord = OAuth2Session(client_id, redirect_uri=redirect_uri, state=session['state'], scope=scope)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/werkzeug/local.py", line 377, in <lambda>
    __getitem__ = lambda x, i: x._get_current_object()[i]
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/flask/sessions.py", line 84, in __getitem__
    return super(SecureCookieSession, self).__getitem__(key)
KeyError: 'state'

code:

lavish prismBOT
#

Hey @slow thorn!

It looks like you tried to attach a file type that we do not allow. We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .m4v, .mkv, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv, .svg, .psd, .ai, .aep, .xcf, .mp3, .wav, .ogg, .md.

Feel free to ask in #community-meta if you think this is a mistake.

slow thorn
#

^ error

vagrant adder
#

the error has something to do with state

#

it says the wrong keyword state

gleaming stag
#

hi. playing around with flask/bootstrap. i have an issue: if i want to run a javascript function right after the view has loaded, jquery and my defined js functions have not been loaded yet. i've found a workaround by wrapping my js calls in a function that does if (window.jQuery)... but that doesn't feel right. if i wait a bit (e.g. if i call the js function in a form, so well after the page has fully loaded), then there is no problem

native root
#

@gleaming stag The reason you're probably getting the jquery not loaded yet issue is your function is running too soon--before the <script src=""> that loads the jquery. You should make sure your javascript is called after the jquery include in your templates, and then things should work just fine. Keep in mind if you're going to be editing the page, you should be wrapping your code in $(ocument).ready() too

native tide
#

@native root was about to say say that. I had some similar problems once i was working with flask for first time .

mild path
#

anyone here use bootstrap studio?

hoary narwhal
#

hey guys I have an problem with videos autoplay in chrome

#

or in anyother browser

#

can you guys please help me

#

ping me please its urgent

bleak bobcat
#

!ask

lavish prismBOT
#
ask

Asking good questions will yield a much higher chance of a quick response:

โ€ข Don't ask to ask your question, just go ahead and tell us your problem.
โ€ข Don't ask if anyone is knowledgeable in some area, filtering serves no purpose.
โ€ข Try to solve the problem on your own first, we're not going to write code for you.
โ€ข Show us the code you've tried and any errors or unexpected results it's giving.
โ€ข Be patient while we're helping you.

You can find a much more detailed explanation on our website.

hoary narwhal
#

what do you mean

#

@bleak bobcat

#

I have an appropriate question

bleak bobcat
#

Then ask it

blissful mural
bleak bobcat
#

None of us here have mind reading abilities yet, we won't know what's your problem until you tell us

valid cypress
#

Does Django migrate overwrite current DB tables (remove data)?

bleak bobcat
#

No, but if you delete a field on your model then the column (and the data associated) will also disappear

hoary narwhal
#

this is the code

valid cypress
#

Ok thanks

hoary narwhal
#

video stops after playing once

#

@bleak bobcat what should I do

#

sorry for pinging you

bleak bobcat
#

What do you want it to do ?

hoary narwhal
#

it is not playing again

#

I need it to play again and again

bleak bobcat
#

So you want it to repeat endlessly ?

hoary narwhal
#

infinite times

#

yeah

bleak bobcat
#

try adding a loop attribute (no value needed) on your video tag

hoary narwhal
#

hmm can you please tell me how

#

I don't know about loop

#

I mean I know

#

but I am not adding it here

bleak bobcat
#

<video controls autoplay loop height="600px">

hoary narwhal
#

this file doesn't have python

#

oh

#

wow it worked

#

thank you so much

bleak bobcat
#

That was the first result on google for "html video repeat" for your information

hoary narwhal
#

I was working on it for days

#

hmm

#

oh

#

I didn't find it

#

on youtube though

#

But I have one question why this feature is only working on Microsoft edge only and not on firefox or chrome

#

is there any specific reason for that

#

or I mean can I enable this for them somehow

gleaming stag
#

hey. i'm starting to teach myself web programming, although i do have some background in python. would you recommend be to use a framework such as jQuery, or should i just use vanilla javascript? or go straight into react or angular? thank you!

rustic pebble
#

Is there a way I can skip the process of changing the script locations in a flask app?

#

for example js/main.js will have to become: {{ url_for('static',filename='js/main.js') }}

rigid laurel
#

@gleaming stag My personal reccomendation is to avoid Jquery and stick to just vanilla JS, unless you need to support older browsers

#

JS has stuff like the fetch API that solves a lot of the problems JQuery was originally good for

tired root
#

@rustic pebble You can change the folder for static files with a config entry, but I'd really recommend using it

#

it makes the app more robust and more secure

rustic pebble
#

yy

#

I will be using it

#

Btw, I am having problem with editing css. It doenst get rendered when I make changes

#

But when I imported my website it loaded the style correctly

tired root
#

Open Developer tools and enable "disable cache when dev tools are open"

#

that solves it

rustic pebble
#

oooh

tired root
latent chasm
elfin lance
#

hi

I'm trying to use flask with socketio, but the clients keeps reconnecting, any solution (replit) ?

gleaming stag
#

@rigid laurel got it! i'll continue my current project in flask/jquery, then after that i'll move on to vanilla JS

inner drift
#

hi guys, does anyone know if I can use login_manager on flask with the pyrebase?

magic blade
#

my django test environment is set to use the dummy cache, and django-imagekit is supposed to use the default cache (in this case the dummy) but when i try to save an image with an imagekit ImageSpec on it in the test environment, i'm getting a TypeError from memcache

rustic pebble
#

Anybody know how to fix this

#

ValueError: Could not deserialize key data.

#

Having problem with JWT

hard elbow
#

Hey!

vagrant adder
#

Hello

hard elbow
#

I have been trying to get help for a lot of time

#

But no luck

#

Here's the question that I asked on stack

#

No luck there too.

#

Posted it in the help channel

#

No one answered.

#

Can someone please check it out?

vagrant adder
#

What does your project structure look like

hard elbow
#

There are the dependencies of flask.

#

After installing flask through pip

#

Than there is a Virtual env

#

That's it

#

I am working on Ubuntu 18.04

vagrant adder
#

What does your project tree look like

#

Files and folders

hard elbow
#

Inside a folder there are all the files related to that project. Including the venv. The flask is installed in venv. Bootstrap is also installed in venv.

#

I'll send a picture for clearer reference.

restive kindle
#

just print screen?

hard elbow
#

@restive kindle sorry, didn't get you?

vagrant adder
#

What's in your app/

hard elbow
tired root
#

ask on their github

crisp hawk
#

Can anyone suggest me a good book/article to help me choose between Flask, Pyramid and Django? I ruled out Django after some research but I'm not even sure about that.

restive kindle
#

Depends what you want to do with it.

crisp hawk
#

Obviously ๐Ÿ™‚

#

ok so to give you more details

#

I have a database, I don't think that changes much for the decision

#

I have some basic visualisation via three.js

#

let's remove the word basic ๐Ÿ˜›

#

and basically I want to connect the visualisation with data from database

#

and do some calculations, so performance matters

#

I created it in flask, but after some research I'm feeling that Pyramid might be a better option

#

but I don't know enough about any of them

restive kindle
#

Do you have knowledge of databases / javascript?

crisp hawk
#

I do

restive kindle
#

Will this be commercial / monetised?

crisp hawk
#

no

#

just a tool for myself

restive kindle
#

Django and Pyramid are both intended for larger projects and come with more caveats so between Flask/Pyramid is up to you.

crisp hawk
#

how do you determine if the project is large

#

๐Ÿ˜„

#

sounds stupid

#

but I mean

#

is it increasing with number of routes or functionality on routes?

#

or both?

vagrant adder
#

Size is determined by usage

restive kindle
#

^

crisp hawk
#

okay

#

thank you both of you

vagrant adder
#

I wouldn't recommend pyramid since there aren't enough docs and articles

#

Unlike flask and django

#

They have huge amount of docs, articles and tutorials

crisp hawk
#

why it bothers me so much is that I wanted to learn a frontend tool since the frontend will be really basic for now so I feel I can get along with something like react

#

so in future if I want to change from flask to pyramid or something, react frontend can be easily adjusted?

vagrant adder
#

Then flask will be just enough

crisp hawk
#

ok ๐Ÿ™‚

#

thank you

vagrant adder
#

Let's say you switch from flask to pyramid, tornado or falcon

#

If you do frontend properly, it won't need any adjusting

crisp hawk
#

that might be an issue ๐Ÿ˜›

vagrant adder
#

Just go for it and don't ve afraid

#

Feel free to come here if you get stuck

crisp hawk
#

wow you are so nice

#

thank you once again

#

I was just worried about the performance of all of this

vagrant adder
#

Flask is very lightweight which makes it very fast

crisp hawk
#

because visualisation seems to be problematic with more data

vagrant adder
#

React could be a bit problematic

crisp hawk
#

and I don't want a tool which will slow me down

#

I don't even know how the frontend tools affect the performance

#

probably won't even need anything since it's all very basic

vagrant adder
#

React is slowest of the bunch

crisp hawk
#

I'm just doing research on everything so I don't miss something

vagrant adder
#

Angular is also a bit heavy

#

Vue and svelte are fast and easy to write

#

Vue has extraordinary docs

#

Like unreal detailed but not dull

crisp hawk
#

sounds great

#

I'll check it out

rustic pebble
#

Is anyone familiar with json webtokens?

vagrant adder
#

And svelte focuses on cutting down developer frustration by cutting down code

#

@rustic pebble sure, shoot

restive kindle
#

Just a question for saki; I have never used a framework for anything. Does Vue etc have a good Single Page Application controller built in?

vagrant adder
#

Yes it does

crisp hawk
#

how about using jquery? performance wise..

vagrant adder
#

Please no

#

Lol

crisp hawk
#

ok ๐Ÿ˜›

#

won't even ask why

vagrant adder
#

It is a bit outdated

#

Pure js can do the job

rustic pebble
#

I have setup a flask server, I am using authlib to generate a jwt and return it

vagrant adder
#

@crisp hawk use jquery if your app is gonna be used on older browsers, it plays nice older browsers

rustic pebble
#

but on return I get this: ValueError: Could not deserialize key data.

crisp hawk
#

if I can do it in pure js then there isn't really any reason to use anything else right?

rustic pebble
#

This is my return jwt function

#
def loginhandler(User):
    headers = {'alg': 'RS256'}
    payload = {'userId': User.username, 'iat': time.now()}
    key = 'Z<"AO3Vs%=}9pD'

    search = session.query(users).filter_by(username=User.username).first()
    if not search[0] or search[1] != User.password:
        print('Wrong credentials')
    else:
        print('User {} has been found'.format(search[0]))
        return jwt.encode(headers, payload, key)

#

@crisp hawk you can do it on whatever suits you, js is just better frontend connection

#

The project I am building rn has js and python as well

vagrant adder
#

I think your User.username could be making problems

rustic pebble
#

User is a class with username, password attributes

vagrant adder
#

Yes

rustic pebble
#
    jwt = loginhandler(User(username=req['username'], password=req['pass']))
vagrant adder
#

Print time.now() and User.username

rustic pebble
#

sure

#

The first two are User.username and time.now()

gritty carbon
#

Hey guys i would like to use Discord login to authenticate on my web site i'm struggling to find any info about it that would be clear for me, any ideas where to look for?

rustic pebble
#

@gritty carbon If you cant find an api then it probably isnt possible

gritty carbon
#

oh i would suspect that my google skills are failing me ๐Ÿ˜‰

rustic pebble
#

@vagrant adder by any chance have u figured it out? sorry for pinging I have been over this for hours

vagrant adder
#

what is time

rustic pebble
#

ooh wait

vagrant adder
#

some module or just something from datetime

rustic pebble
#

time aint serializable

vagrant adder
#

that's it

rustic pebble
#

I have just done

#

from datetime import datetime as time

#

I have a custom cls

vagrant adder
#

json accepts strings, ints, floats and arrays

rustic pebble
#

This works

#
class DateTimeEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (datetime.date, datetime.datetime)):
            return obj.isoformat()
vagrant adder
#

try time.now().isoformat()

#
>>> from datetime import datetime as time
>>> time.now()
datetime.datetime(2020, 2, 29, 11, 55, 22, 903945)
>>> time.now().isoformat()
'2020-02-29T11:55:30.322009'
rustic pebble
vagrant adder
#

there you go

rustic pebble
#

yup works

vagrant adder
#

and now it should be as a string

rustic pebble
#

So this: str(time.now().isoformat())

vagrant adder
#

is same as time.now().isoformat()

#

i mean you can definitely protect it to be sure but docs say in python3 that isoformat returns string

rustic pebble
#

Well it did

#

for ur eval

vagrant adder
#

i have very similar thing in my last project that saves isoformat as string into database

#

and it works just fine

rustic pebble
#

Hmm

#

same error

#

ValueError: Could not deserialize key data.

#

I have a exactly the same thing in my previous project but I was using datetime as a request param

vagrant adder
#

that's the error with time.now().isoformat() ?

#

try str(time.now().isoformat())

rustic pebble
#

yup

#

i tried with stras well

#

same

#

Thats weird

#

@vagrant adder I found the error source but I dont know how to fix it

#

basically key is the third of these

    headers = {'alg': 'RS256'}
    payload = {'userId': str(User.username), 'iat': str(time.now().isoformat())}
    key = "zmD4BnktqeG6yX67dtSx"
vagrant adder
#

and the key is the error?

rustic pebble
#

They key is the error

#

But everything I change it to

#

Returns the same

vagrant adder
#

Ask on SO, i'm a bit busy rn

#

If i figure it out i'll ping ya

rustic pebble
#

Sure

chrome dawn
#

Is it essential to know languages like CSS, JavaScript, PHP for any programmer?
HTML too

vagrant adder
#

Nope

#

Programming is a broad term

#

There are a lotnof branches of programming

rustic pebble
#

@vagrant adder I found it, basically I need to add a private.pem file which I have no idea how to generate

#

loveable

vagrant adder
#

Web dev, game dev, data engineer, devops, database engineer etc

chrome dawn
#

I see a lot of jobs requiring the ability to create a website although the field itself doesn't involve web development

vagrant adder
#

I'm assuming you are focusing on web dev

chrome dawn
#

nope

#

machine learning, data, ai

vagrant adder
#

Okay

#

If we are talking about generic programming, then no, php,html,css aren't necessary

rustic pebble
#

php isnt needed at all if you use python

vagrant adder
#

@rustic pebble nice

rustic pebble
#

Do you by any chance know what a .pem file is?

vagrant adder
#

nope

rustic pebble
#

If I want to grab a token that is saved in the cookies with flask

#

How would I do it

bold mortar
#

hi

#

i am getting 'Response' object is not subscriptable

#

city_weather = {
'city': city,
'temprature': r['main']['temp'],
'description': r['weather'][0]['description'],
'icon': r['weather'][0]['icon'],
}

#

in this code

#

how can i fix this?

quasi ridge
#

you probably want to use the .json method on the response object

bold mortar
#

aha

#

actuall i need to render this in template

quasi ridge
#

well perhaps that too

bold mortar
#

@quasi ridge you know how can i fix this?

quasi ridge
#

I just told you

bold mortar
#

that was solving

#

?

rigid laurel
#

Its very unclear what you're actually asking

#

I'd suggest try rephrasing it and give a clear example of what you want

bold mortar
#

okay

#

look this you will probably understand

#

i am not rendering

#

i just need print data in terminal for check

#

and?

#

anybody help?

heady thorn
#

Hi all. Is there a flask channel?

restive kindle
#

No, questions about flask can go in here.

#

Or in the active help channels.

bold mortar
#

nobody can solve my problem?

rigid laurel
#

At the bottom in your return, you should change it to be return render(r.json(), 'home.html') and get rid of everything between the two prints @bold mortar

heady thorn
#

Great thanks all!

bold mortar
#

@rigid laurel i dont need render

rigid laurel
#

then what do you want?

#

just to print the response?

bold mortar
#

i need print that in terminal

heady thorn
#

No, questions about flask can go in here.
@restive kindle thanks sir

bold mortar
#

i am checking data yet

rigid laurel
#

ok, after line 7, do print(r.json())

bold mortar
#

this will print all data?

rigid laurel
#

Yeah

#

You're probably best of waiting a little while Stew

#

otherwise it will get lost in the current question

#

is my guess at least

bold mortar
#

but i dont need all data

heady thorn
#

Hi all, I'm new here. Vue developer. Looking to build a new app with lots of maths and charting requirements. I'm thinking Vue frontend with flask back end! As I believe flask is great for the back end maths etc. A good plan?

bold mortar
#

city_weather = {
'city': city,
'temprature': r['main']['temp'],
'description': r['weather'][0]['description'],
'icon': r['weather'][0]['icon'],
}

#

i need only this

#

line 9 works for print all data

rigid laurel
#

Ok, for what you want

#

you can do respones = r.json()

#

than you can access all the data as though it were a dictionary

#

e.g response['main']['temp'] as you're doing

vestal hound
#

@heady thorn if it's plotting you want, you can look at Dash too

bold mortar
#

okay i will try