#web-development
2 messages ยท Page 42 of 1
Lol
Lel top kek
'Summoning' ๐คฃ
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.
- 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. - How could I import this
appvariable from the modules within the package so can access theapp.configvariable.
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")
Made this pure css accordion: https://jsfiddle.net/q07dx1nw/
Use it as you see fit, if you want to.
I thought it was gonna use https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details but the checkbox trick works too ^^'
Do you use Django CMS?
True, and it's not even edge compatible anyway
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
Yeah, they rewrote Edge a while ago to use Chromium
I wasn't even aware, I didn't have a lot of time to spend on frontend recently ๐ฆ
@tired root https://codepen.io/qvolant/pen/gOpMNPx
Oh, yea, not checkboxes, radio
But same principle
nice
but yeah, radios work better if you want only one open
could use that with a accordion too
I would animate the transition to make the change more apparent
but I dont think there are any issues with it
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
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
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
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'))
@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
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
hello daggy
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
@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
i have no idea, never consumed any xml api
damn it
@shadow orchid You need to look at their documentation
Generall API's like that work by querying urls with the information
i do not understand
and that works both ways
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
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
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.
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
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 want to run my django project under gunicorn on localhost. I installed and integrated gunicorn. When I run:
python manage.py run_gunicorn
It works but there are no any static files (css and js)...
The top answer links to here https://gunicorn.org/index.html#deployment
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.
@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
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.
https://pypi.org/project/django-model-utils/
also suggests that 3.0 is supported
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?
https://nickjanetakis.com/blog/server-side-templates-vs-rest-api-and-javascript-front-end - spitting facts
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
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
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
If you're gonna return html use https://docs.djangoproject.com/en/3.0/topics/http/shortcuts/#render instead
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...
@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
I was talking to TLS ^^'
Oh my bad.
Do you want your view to return an image or html with an image tag ?
@bleak bobcat not an image. Image must have some link alongside with it. So i am passing context on DetailView
So like offby1 said, return html with a <a> tag containing an <img> tag ^^
@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
I was recently trying to figure out Django. I don't understand the function of models.py.. can someone help?
where is this file?
its actually models.py sorry
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
right so you don't understand models @normal blade?
yep
It's basically an ORM
Just classes that represent data in your database
make storage of data super easy
does models link it with sqlite?
I'd reccomend reading https://docs.djangoproject.com/en/3.0/intro/tutorial01/
okay thanks ๐
and going through them all, they're quite helpful
Cool!
but it's basically a python interface to interact easily with whatever database engine you use
you'll understand after a few tutorial pages
gotcha!
@normal blade models are a chain between python code and your database
it writes raw sql queries and fetches given data back to you
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
probably yes
discord has very complex database architecture but you can try to mimic it
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()
so TodoItem is an object with content attribute
and it gets content value from a database
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
yes, it will work
it's up to you to set up the logic behind the view, but that's th concept
okay perf thanks!
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
You can try https://python-zeep.readthedocs.io/en/master/
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
i actually want the navigation bar to be a whole different style when it is not on the home page
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?
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)?
Would a through model be used here?
With the the through model having a choicefield?
@keen bone i would suggest taking a look at corey's schafers youtube tutorial series
Sounds good Damian, yea, that's what through model are made for
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 https://api.jqueryui.com/dialog/#option-autoOpen
๐ค Thanks for the quick reply @bleak bobcat. But the contents are still showing, even before the dialog opens.
You need to initialize the dialog with that option on page load (not after 5sec), and then after 5sec you call the open method
Well damn, it worked. I feel dumb now lol, thank you @bleak bobcat
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.
Oh god. Have you considered using SQL to help keep the databases ?
hah I do use sql on the backend its just its scale and relations make it hard for basic forms to implement
I see. Well I'm not sure I'm much help, my javascript and SQL knowledge is awful at best.
๐
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! ๐
hahha thanks, im close
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
checked /var/log/apache2/error.log?
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'
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)
Hi guys, Have any of you used Odoo/OpenERP or ERPNext?
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
Just add it in your links ? I don't understand why you'd want that but ok : https://www.python.org/#
are you talking about fragment identifiers?
@wise yacht Apache/Nginx rewrite rules
Take a gander at mod_rewrite and the corresponding htaccess rules
@tired root I will look at Apache/Nginx rewrite rules
@vestal hound Hi to be honest im not sure.
hi
i did everything properly of this https://github.com/geex-arts/django-jet
im getting this error
im using latest django, and python 3.8.1
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
xd yes
xd yes?
yes. but that's weird
Can anyone help me with an issue regarding flask here?
!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.
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?
@native tide if you use more stable version 3.5 it may be ok
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
Is there a website that displays a good contrasting colour to a provided one?
@haughty saffron maybe try http://paletton.com/#
In love with colors, since 2002. A designer tool for creating color combinations that work together well. Formerly known as Color Scheme Designer. Use the color wheel to create great color palettes.
thanks
@haughty saffron
https://colorhunt.co/
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?
oh got it
Anyone has experience to setup Django with Apache2?
!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.
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
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
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)
user may differ for you
Thx
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?
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
@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?
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
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?
@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
@native tide this works even if my URL will all direct to the home root?
sure - why not?
Please give me a proper example of what you want to achieve
$.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':
@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
actually. I don't think I should be using ajax for this. Going to turn to javascript and mysql
@shadow orchid nice.
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?
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?
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
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)
Use a web server
don't use python for that
Apache, nginX can each hold a lot of connections.
Eeeem, its kind of complicated to explain, but I need to have many session BETWEEN MY SERVER AND GAME SERVER
and thats the problem ๐
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
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?
threads have limits
with 2 physical threads, if im correct, i can get up to 5 functions running
Python can spawn 255 threads
if your computer will be able to handle it is another question, depending how heavy the computing load is
how are sleeps done?
if I spawn 100 threads with 100 sleeps, is it "counting time" on every thread?
every thread needs to call time.sleep(x) in his own context to yield the remainder of it's quantum to another thred
I still dont understand, I was not able to run more than 5 functions (on one-core-cpu), however, cpu usage was ~1%
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
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
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
Anyone have a good recommendation for a Flask tutorial?
@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
For admin interfaces, should I better make mh own solutions without any plugins or use something like flask_admin?
@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...
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
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.
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.
For example: when i copy paste code but i don't even understand it?
It worries me sometimes .hehe
it should
What would be a good api to scrape weather information from a website?
other than bs4
Why would you scrape that?
@tacit current darksky has a proper API; it's not hard to use
Practically no websites will allow you to scrape like that, and this server can't help with something that breaks tos
no scraping needed
OH.
Openweatherapi is very easy to use
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
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
so I am using django with docker and my staticfiles are missing in my container but the admin files are there??
https://puu.sh/FdZvd/8be360528a.png
All this disappears and gets replaced by an admin folder containing the admin static files
STATIC_URL = "/staticfiles/"
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "staticfiles")
]
my staticfile settings in my settings.py
you certainly can but config.py is commonly used for specifying app configuration, not instancing other flask extensions
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=
Did you do something like request.POST['some_key'] @bold mortar ?
You need to do request.POST.get('some_key', some_dafault_value)
i checked that too
Then code + stacktrace pls
Have anyone used ckeditor_uploader for django CMS here?
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>
Are you using jinja?
@haughty saffron
Normally one is using templates for stuff like that
in jinja for example: {% include('yourfile.j2') %}
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
thanks
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
ohk ty
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
Is this function being called every request? There is no function to check whether the user already exists.
@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
anything like that except for flask?
Flask limiter
@bold citrus
I think he means creating flow/queue rather than concurrent requests.
Task queue?
I think you would have to implement something like this outside of flask.
Yeah, i can't find anything that limits rate based on queue
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.
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
Im not exactly a python programmer as such so you are probably right. A fifo queue should be simple to implement tho
This article implements waiting queue
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.
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
Alright, thanks
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
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")```
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?
Anyone know why this throw me: NameError: name 'self' is not defined ?
then I get AttributeError: 'ForwardManyToOneDescriptor' object has no attribute 'title'
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)
@patent cobalt thanks for this great answer!
I found that this solution is even in django docs
@patent cobalt Can I somehow define this function ones and add this to many models (be DRY )? Something like that: https://pastebin.com/qDATkd7F
sorry, forgot 'self'
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
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
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
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>
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.
erm -- looks like Authlib is the way to go. i'll post again if i run into issues. thank you
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
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
you can't query from html
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?
are you using flask or django
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?
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
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*
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?
Have you tried changing the order, they might be blocking?
i tried, but i just confused myself more
Ah, try changing to max-width, as it wont display if the browser's viewport is too small
how can i have chrome show me the size of itself?
I believe its ctrl shift m for firefox, then select responsive and you can set the size
<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
Odd, had you reloaded the page?
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
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>
ok thanks
so how does that affect whether i use min or max
should there only ever be one max?
one min?
So, max us easier to understand when you are looking back weeks/months later, as it is readable
And makes some sense
so i should only use max?
You probably could, as you have a fallback image.
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
oh, right, css
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
Ok, so the css for something like this would look like this:
picture source {
height: 300px;
}
but how would that allow my 2nd and 3rd options be 400px and 500px respectively
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
An example of a media query would be:
@media only screen and (max-width: 600px)ย {
ย picture source {
height: 300px;
ย ย }
}
well not the same size as each other, but the same size they were already
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
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
appreciate the help
Is it working?
not the 300px, 400px, 500px stuff, but i believe i understand the picture tag better now
i shouldve been using fire fox
ยฏ_(ใ)_/ยฏ
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
<!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
You don't appear to be closing your source tags with </source>
Which means you are nesting them
Same with img
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
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
ok sorry, no, she meant to edit it in photoshop and have that be the 300, 400, 500px
so, yeah, this works now thanks
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;
}
}
I found this https://www.freecodecamp.org/news/the-100-correct-way-to-do-css-breakpoints-88d6a5ba1862/ very useful
thanks for the reference
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?
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
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
for more info: https://docs.python.org/3/library/queue.html
@vagrant adder About the querying that I asked about yesterday, I am using flask.
I am having difficulty understanding https://docs.djangoproject.com/en/3.0/ref/urlresolvers/#django.urls.reverse this function's utility. It is used in this example https://docs.djangoproject.com/en/3.0/intro/tutorial04/
Maybe I'm just tired but I'm not seeing what it's doing or what you want what it seems to describe.
that is the django.urls.reverse() function
the top answer explains
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.
true
How did you use my code? The
innername 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!
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 ?
Is that a good idea to mix for example wtforms with just regular custom forms?
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
@manic ravine form action="/"
action={{ url_for('home') }}
url_for('home') will return what you set as @app.route() argument
In this case just "/"
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.
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 ๐
.
โโโ 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
Thank you. I think I've created some kind of circular import issue but I think I'm closer.
implement an api key for your app
the key (in theory) is only known / accessible by the user that generated it or that it was generated for
yep
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
@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
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)?
@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)
Sweet thanks. Seemed like the most straightforward solution
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."
create a new class and inherit the user class and edit the functions
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
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?
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
So you want a 'framework' to develop a UI or a website design
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
for website designs you can use psdfreebies but read the license before using
web frameworks can be angular.js, vue.js, react.js
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
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.
Its pretty hard to figure out what is/isn't valuable without a specific goal in mind
Whois history im sure is a premium feature so maybe just catalog whois data for sites
@Charlie It's project to train Python so all kind of info which is worth saving
Train python? A NN?
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
@Ccb14 I'm sorry I meant to train programming in Python not NN
yeah, do what charlie suggested
@Charlie Thats a Long-term project to train different areas but mostku data scrapping and ML
*in diffrent areas
๐ฉ why does most flask tutorials not use app factory pattern? Even worse, some of them write all in one file
@Charlie Ill propably go for it, thanks for advice 
@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
Yea maybe
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
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.
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
[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:
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.
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
@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 root was about to say say that. I had some similar problems once i was working with flask for first time .
anyone here use bootstrap studio?
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
!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.
Then ask it
None of us here have mind reading abilities yet, we won't know what's your problem until you tell us
Does Django migrate overwrite current DB tables (remove data)?
No, but if you delete a field on your model then the column (and the data associated) will also disappear
Ok thanks
video stops after playing once
@bleak bobcat what should I do
sorry for pinging you
What do you want it to do ?
So you want it to repeat endlessly ?
try adding a loop attribute (no value needed) on your video tag
hmm can you please tell me how
I don't know about loop
I mean I know
but I am not adding it here
<video controls autoplay loop height="600px">
That was the first result on google for "html video repeat" for your information
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
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!
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') }}
@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
@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
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
Open Developer tools and enable "disable cache when dev tools are open"
that solves it
oooh
Chrome
hi, can you help me with opening file in binary mode instead of utf-8?
traceback: https://paste.mod.gg/qecixaxipi.sql
code: https://paste.mod.gg/ufixejenex.py
(I have django.REST.InMemoryUploadedFile and want to send it to another api)
hi
I'm trying to use flask with socketio, but the clients keeps reconnecting, any solution (replit) ?
@rigid laurel got it! i'll continue my current project in flask/jquery, then after that i'll move on to vanilla JS
hi guys, does anyone know if I can use login_manager on flask with the pyrebase?
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
Anybody know how to fix this
ValueError: Could not deserialize key data.
Having problem with JWT
Hey!
Hello
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?
What does your project structure look like
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
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.
just print screen?
@restive kindle sorry, didn't get you?
What's in your app/
ask on their github
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.
Depends what you want to do with it.
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
Do you have knowledge of databases / javascript?
I do
Will this be commercial / monetised?
Django and Pyramid are both intended for larger projects and come with more caveats so between Flask/Pyramid is up to you.
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?
Size is determined by usage
^
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
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?
Then flask will be just enough
Let's say you switch from flask to pyramid, tornado or falcon
If you do frontend properly, it won't need any adjusting
that might be an issue ๐
wow you are so nice
thank you once again
I was just worried about the performance of all of this
Flask is very lightweight which makes it very fast
because visualisation seems to be problematic with more data
React could be a bit problematic
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
React is slowest of the bunch
I'm just doing research on everything so I don't miss something
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
Is anyone familiar with json webtokens?
And svelte focuses on cutting down developer frustration by cutting down code
@rustic pebble sure, shoot
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?
Yes it does
how about using jquery? performance wise..
I have setup a flask server, I am using authlib to generate a jwt and return it
@crisp hawk use jquery if your app is gonna be used on older browsers, it plays nice older browsers
but on return I get this: ValueError: Could not deserialize key data.
if I can do it in pure js then there isn't really any reason to use anything else right?
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
I think your User.username could be making problems
User is a class with username, password attributes
Yes
jwt = loginhandler(User(username=req['username'], password=req['pass']))
Print time.now() and User.username
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?
@gritty carbon If you cant find an api then it probably isnt possible
oh i would suspect that my google skills are failing me ๐
@vagrant adder by any chance have u figured it out? sorry for pinging I have been over this for hours
what is time
ooh wait
some module or just something from datetime
time aint serializable
that's it
json accepts strings, ints, floats and arrays
This works
class DateTimeEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj, (datetime.date, datetime.datetime)):
return obj.isoformat()
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'
there you go
yup works
and now it should be as a string
So this: str(time.now().isoformat())
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
i have very similar thing in my last project that saves isoformat as string into database
and it works just fine
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
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"
and the key is the error?
Sure
Is it essential to know languages like CSS, JavaScript, PHP for any programmer?
HTML too
@vagrant adder I found it, basically I need to add a private.pem file which I have no idea how to generate
loveable
Web dev, game dev, data engineer, devops, database engineer etc
I see a lot of jobs requiring the ability to create a website although the field itself doesn't involve web development
I'm assuming you are focusing on web dev
Okay
If we are talking about generic programming, then no, php,html,css aren't necessary
php isnt needed at all if you use python
@rustic pebble nice
Do you by any chance know what a .pem file is?
nope
If I want to grab a token that is saved in the cookies with flask
How would I do it
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?
you probably want to use the .json method on the response object
well perhaps that too
@quasi ridge you know how can i fix this?
I just told you
Its very unclear what you're actually asking
I'd suggest try rephrasing it and give a clear example of what you want
okay
look this you will probably understand
i am not rendering
i just need print data in terminal for check
and?
anybody help?
Hi all. Is there a flask channel?
nobody can solve my problem?
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
Great thanks all!
@rigid laurel i dont need render
i need print that in terminal
No, questions about flask can go in here.
@restive kindle thanks sir
i am checking data yet
ok, after line 7, do print(r.json())
this will print all data?
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
but i dont need all data
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?
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
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
@heady thorn if it's plotting you want, you can look at Dash too
okay i will try