#web-development
2 messages ยท Page 46 of 1
Do it.
I would have a script on python do that
scan through the line of all your html files
Its most likely a feature of whatever editor you use already
and replace the urls with that
np
There is a part of me that wants to take the time to pick up sass. But I also feel like its so unnecessary, especially as I dont exaclty want to focus on front end. I would rather tweak someone elses CSS that start from the bottom, at which point sass seems really useful.
unnecessary for me*
obviously people out there writing css from the bottom should learn it
This is in my forms action
/post?id={{g.id}} but for some reason it isnt adding the id argument
Is that in a template?
yea
its not adding the ?id at all
Try to print g.id in the html to see if its being passed the variables. It probably is if its missing ?id=
But just to be sure
It might remove ?id= if its getting nothing as a value tho
if you're using django you can probably use {% url 'template_name' g.id %}
I think
But you have to assign a name to that route in the urlconf
im using flask
ah ok nvm
Its still not adding the arg
Did you try displaying it in the html somewhere to verify that the template is getting the object?
Or is it displaying any other variables?
In flask, do you pass a template its variables from the route/view?
@native tide seems like .id is an attribute to g why not try rendering the jinja template with .id pre-given
Show me where you set the g value, @native tide
If you do it with current_app.context(): that creates a new context
You guys make me want to look at Flask everyday
haha
I changed it to just have {{id}} and it's printing the right if
Id
Sorry for the long response
Even if it was printing none it'd still do ?id=None
do i need to add something ? related on the endpoint?
hmm
seems the url wont change at all in the form
what is the full code for the entire element?
a button element?
I have this going on in mine <a href="?page={{ page_obj.paginator.num_pages }}">Last</a>
So it should work.
Nevermind mine was messed up
i couldn't figure out how to do the ? thing though in my app.py
Is it possible to keep changes made to the current_user with flask-login
I am trying to change a property but the changes are not saved when it is accessed from a different route
How does one use the Django 3.0's models.IntegerChoices when declaring a model?
Argh
So you don't know if it is possible?
I'm desperate at this point. Just rewrote a an entire thing to use flask login]
I guess the real question I am asking is is it possible to store a Python class, similiar to how you can store normal values in the session variable using Flask
Cause I have a class with way too many variables and stuff to manually convert into JSON
And cookies == session right?
Kinda
well is there a way to store a class in cookies
If you use cookies make sure to sign them using a JWT
There is a way to store user data in a cookie
Then after getting it you can recreate the user class
what is this way
Look up how JWT and flask cookies work
kk thanks
You will find it quite easy
@opal radish Anything on side of the user is to be considered unsafe and compromised
so storing classes there is kind of a stupid idea, to be blunt
and storing the state of classes is a bad idea in webdev in general
store the data, but in a database as atomic values with relations
one value per database column
first and last?
For my last project i used jwt for auth
yes @opal radish
Worked wonderfully
I use discord oAuth for this project,
don't store the credentials in a cookie
save the bearer token and the refresh token in a database
ye no worries.
@tired root storing data such as usernames in a signed with private key jwt cookie
Isnt exactly unsafe lol
Ofc you are not going to add pws on that
but storing pickle is
I dont use pickle
and usernames aren't sensitive no
but tokens are
I mean I have a knowledge of what it is
But I know people dont suggest it
So I guess that it isnt good
That is what I mostly use
Serializing means putting an object as it is into a format that can be read back. Many games do this and save their entire state to the disk, so they can reload it later
also known as quicksave
if one were to edit that data, you could theoretically execute arbitrary code
in a remote context, using that is undesired, to put it mildly
Yeah but even then I also store the token value in a something I call server side cookie and each time a user requests something that needs more than guest permissions the two tokens get compared
If the client one is changed it logs the user out
storing something and using pickle are 2 totally different things
I am talking about jwt
jwt plays no role here
Sure
??
I have a chatbot that works on WebSockets. For the client who is on a website can easily connect. (As session would stay connected in browser)
But for the client who is conversing through APIs (in case of WhatsApp) there needs to be a middleware that will do this.
So for each client, there should be active WebSocket connection. If the same client is sending the message, the old connection should be used and respond.
How do I do this
You want to recover a WebSocket connection?
Yes, kinda
If a same user sends a request again I wanna use the same connection
consider there is a unique id for each user in the API request @jagged lark
You can't really recover a WebSocket connection, at least not easily, you'll be better creating a new one using the same ID
I don't think that will help
Creating a new websocket connection would reset the context
hi_flag = False
message = await websocket.receive_bytes()
if message == "Hey":
hi_flag = True
reply = f'hey, there {user_id}'
await websocket.send_bytes(reply)
message = await websocket.receive_bytes()
if message == "hey":
reply = f'Hey you already said Hi ! WTH !'
await websocket.send_bytes(reply)
if message == "Goodbye":
if not hi_flag:
reply = 'Hey You did not say HI !'
await websocket.send_bytes(reply)
Consider this example @jagged lark
This is a pseudo code
what if I want a middle ware
It will get a API request with a unique USER_ID
After sending the message that API will return the response
If I get the same USER_ID again it should use the same connection since if you see the pseudo code above, you'll get it
By definition, you can't recover a WebSocket connection, you need to reopen it
Yes you can have the client send you the same ID
Yes
Hence it would not wokr
If the connection drops for whatever reason, the connection is dead and you need to open a new one
There should be a way out for this?
I mean, the client could simply store the ID and use it to reopen the connection
How do we do tha
that
open a connection where ID is known
because when I connect there is no option to mention the websocket number / id number it should connect
You can supply parameters through the url, the same way as you do with http
I think you are misunderstanding the problem
hey guys can i ask question now or there is some case open?
cause it's hard to tell for me ๐
You're probably ok to ask
Ok thanks
so i have problem with circular import in my models i was searching for solutions and i found 2 :
- to use path to model instead of importing it
It does not work for some reason when i do
games_subbed = models.ManyToManyField(posts.Game, related_name='subbed_game')
i'm getting error :
NameError: name 'posts' is not defined
Yes apps are in proper order
- Second solution is to use
apps.get_model()
but that doesn't fix my circular import problem
i can throw my files to some paste.bin if needed
but TLDR :
localusers/models.py ->
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.apps import apps
games_subbed = apps.get_model(app_label='posts', model_name='Game', require_ready=False)
...
class LocalUser(AbstractUser):
verified = models.BooleanField(default=False)
servers = models.ManyToManyField(DiscoServer, through='Membership', related_name='servers')
games_subbed = models.ManyToManyField(games_subbed, related_name='subbed_game')
...
posts/models.py ->
from django.db import models
from localusers.models import LocalUser
# Create your models here.
class Game(models.Model):
title = models.CharField(max_length=200)
image = models.ImageField(upload_to="images/")
def __str__(self):
return self.title
class Event(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
start_time = models.DateTimeField()
end_time = models.DateTimeField(null=True, blank=True)
game = models.ForeignKey(Game, on_delete=models.CASCADE)
creator = models.ForeignKey(LocalUser, null=True, on_delete=models.CASCADE, related_name='creator')
players = models.ManyToManyField(LocalUser, null=True, related_name='player', through='Participation')
...
problem is that Event need LocalUser
and LocalUser need Game
is calling models by appname.modelname not working anymore?
ahh forgot about traceback but it's quite enigmatic
Hey @gritty carbon!
It looks like you tried to attach file type(s) that we do not allow (.txt). 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.
ImportError: cannot import name 'LocalUser' from 'localusers.models' (/home/duskhorizon/Desktop/discoplaytogether/localusers/models.py)
is at the end no matter if i do circural import by purpose
or i use getmodel()
that is confusing me
but when i remove any mentions of 'Game' it works as charm
i had spend some time fixing that any contribution would be appreciated
Great!
Heya guys, I'm wondering what the differences are (in general) between a shared hosting, a virtual private server, and dedicated hosting when it comes to direct control with SSH.
- If my shared hosting provides an option to control my "share" of the machine, what limitations should I expect? I'm guessing since they're running on the same machine without a virtual server -- I would not have root access and would be limited to my own folder, right? Is there any way for them to give me root access anyway? Any other limits?
- As for VPS vs Dedicated hosting, are there usually any differences between the two when it comes to control via SSH?
My hosting experience is limited, but I once I had shared hosting with HostGator where they gave me ssh to my own folder, but I literally had to call them an sit on the phone for an hour everyday to get it working. Then by the end of the day, they would be blocking my connections again, and I'd have to call the next day. Do not recommend them by the way. That was when I was less informed.
That isnt even the worst thing about them. The worst thing is that they try to sell you the least secure setup they have for an outrageous price and then act like security is an extra feature that not everyhone needs.
Like they want you to pay for SSL. lol
how can i do some sort of asyncio.sleep() but in javascript?
what are you actually trying to do?
you can do ```js
setTimeout(() => {alert('delayed')}, 5000);
I don't think that should block any other code @haughty saffron
@native tide I think learning React (or possibly Vue or Ember or another web app framework) is probably the most useful next step from Django. It lets you take a step from building websites to building web applications. Also by learning React, you learn just general JS pretty well in the process.
I don't think there's a huge amount of value in learning Flask if you don't find yourself disliking Django, a lot of the core ideas are very similar.
Learning React exposes you to a new way of doing things, but at the same time doesn't throw away what you've learned so far.
I'll also ad the caveats to this that I've written more JS than I have Python, and I've not got a huge amount of experience with react, Django or Flask - but I am comfortable with all 3
I'm more or less on your train of thought though. Even if I eventually dont want to rely heavily on JavaScript anywhere that I don't need to, the entire web is using it a lot, and I need to be familiar with it. In fact I know that several things I want to do can only be done with it. If it will help me improve my vanilla JS in the process, that's great. I'm mainly hoping that whatever JS I want to add will integrate with the SS rendering I would rather do where ever I can.
But yeah, you've sold me that its a good next step.
Are React docs as good as Django docs?
I find that with frameworks that are rapidly developing new features its best to learn it directly from the makers
React docs are pretty good for the very early stages of learning. But once you have the basics down, it gets a bit iffier
Yeah, well, that's Django too. You just have to get good at reading code at that point.
I learned React by just being thrown into the deep end by having to work on an app that was in production - so my learning experience was pretty atypical
yikes
hey guys , I need to log database queries to log file and i'm usng django db.backend to logger
the problem is it logs all queries at DEBUG level when i make error with raw sql
shold i ovveride the CursorDebugWrapper to log as ERROR level log if so?
Thanks for the tip TLS, that doesn't sound pleasant, I'll avoid HostGator's shared hosting then
To be fair, I think they didnt like my VPN. But shrug.
Still better options
So, this doesn't work if I turn off the Babel preprocessor. Is that typically what you need to use React? I would prefer to work somewhere that is not this little website's fiddle.
How would you go about setting up this environment.
In fact, that's one of my least favorite things about JavaScript is I want to work in real editor that otherwise perfectly emulates the browser environment
Has anyone used a payment gateway to both 1) charge service fees on each transaction and 2) also accept paypal? What gateway did you use?
Maybe, the payment gateways has a specific apis. I think you need create different url for each payment. In Brazil we have a PagSeguro and others easy ways
Hmm, so I'm wondering how websites are able to charge service fees as well as take Paypal. As far as I can tell, no gateways, including Braintree, allow for both. So how would a site take paypal and also impose a transaction fee?
Why impose that fee at all?
Because webdev lol.
The web used to be a more decent place. There were less people on it. Sure it was still heavily made up of porn and other shady things, but the entire web wasn't a giant screw in the face. I know that there is no use living in the past, but some things about the old web were better
That's why when people come to me and say, "This is how we're developing today," I dont necessarily want to be exactly like them.
That being said, I have started my React lessons.
I'm having fun with it.
what in the actual f
These are all the node modules installed by npm's create-react-app
Is this really what you have to deploy with every react app?
That is not sane.
@native tide Now you know why I avoid npm and react
jesus christ
Not only the sheer amount, but those tools have a history of malicious packages
Yeah all my friends of hackers.town hate it too
and people importing 2 line addons because they are too stupid for an if
I am blown away
I'm still gonna play with it because I dont want to be ignorant
But wtf
lol
Is there a more light weight manner of setting up a react environment than this huge massive amount of things?
Because this was automated for me.
If I could do this manually in a more sane manner, I would prefer that
Honestly, I'm pretty sure that I'm going to come away from this only more strongly feeling how I already feel. But I know that everyone uses this so Im gonna learn it. But... I imagine myself just using vanilla JS and server side rendering to be honest.
I dont even think jquery is this big
Maybe its more broken but
I used to think that the reason they pack out JS in the minified form was to obfuscate the code.
Which Im not entirely convinced isnt part of the reason
But i see that the main reason
Is that this is too fucking big
It cuts down the size
obfuscation is a side effect
You should btw always look for ways to minify your code, html or js or css
I realize that now. I used to think it was intentionally trying to obfuscate, but it makes sense now that I see how massive these things are.
When I turn off flask-minimize, my web page has 89 lines
60% is white space
from the template generator
Right.
Lets say that I only import half of these modules in any file in the app
Is there going to evertually be a way to pack it out only with what Im using?
I don't know tbh
never really used react or npm
as in, doing more than taking a gander
I have it mainly for tools on my pc
I kind of want to make certain interactive experiences in a web game. But what I definitely don't understand is why you would use this to make a common document page.
Its like using a flamethrower to kill a roach
Either way im gonna learn this stuff so if for no other reason
Im not the person hating something I dont know anything about.
What I'm really hoping for is that 90% of my site can be a document based, template rendered from server python app...
But that on certain pages
I can initiate little JS experiences, save the results of them to database, and move on.
I dont need to constantly be XHRing the server to load new shit on the same page
On my skill queue, I have a progress bar
it shows how far a skill has progressed in training
The API request has start and end date, if it is training
I am using the template generation to set that bar to the progress relative to start and end
it persists between refresh and the browser animates it on it's own
Javascript: 0
@keyframes progress-bar {
from{ width: {{ training_percent }}%; }
to{ width: 100%; }
}
.progress-bar-container .progress-bar{
position: absolute;
background-color: #66fcf1;
top: 0;
width: 20%;
height: 1.75vh;
z-index: 1;
animation-duration: {{ training_seconds }}s;
animation-name: progress-bar;
}```
Interesting. You can do a lot with CSS.
Ive never used keyframes in CSS before. I should look into that
I didnt realize you could template render css.
thats a great idea
No, I render that into the head
ahhh
with a <script> tag
the browser interpolates the values between the percentage points between the keyframes
so you can give it from 0-100 or more points to interpolate between
I might snippet save that.
the template generation code is quite big though for that
but then,it needs a lot of logic
it's my heaviest page so far
190 lines of python
So keyframes is for defining the name of an animation?
well, for the whole calendar
yes
you can apply that animation to any element
that supports the animated values
what triggers the animation? On load or appearance of the element?
if the element is visible on load, the load
ok
the animation happens as soon as the element is in the DOM
got it
nah. for JS you mean?
yeah
I haven't really used a lot of JS in general. I've gone over the basics. But Ive never used it to build anything, mostly because it annoys me.
But I think part of the problem was I was approaching it wrong
and by gone over basics I mean, I am familiar with the syntax enough to read it.
But I have never built anything using it
Other than like
Grab this div, make it appear when I do this.
Kind of thing
This is going to be very difficult to make
Because every skill has a depedency
not sure how to implement that in js
probably need to xhr the flask app and have python resolve it
I imagine that will be my goto constantly.
Damn, I have to get to bed. Its late af over here.
I'll see ya
o7
Today i've just updated vs code, and i have a strange "problem" with directory
Why static and style, that are 2 different folder, are on the same line? How can i set the preferences that folder are not inline?
It doesnt obv create errors, but it confuse me. I'm used to seeing them on different lines
I solve the problem with this https://stackoverflow.com/questions/59477289/turn-off-visual-studio-code-inline-parent-child-folder-display Probably, after new vs update, the way how they are displayed is changed
Anyone using pycharm ?
Should i go for pro ? Been using community version for some time and i really like it
i have never liked ide's in general
@native tide
Yeah im kinda interested for that flask support tho
Flask support is great
supports jinja and recognizes missing tags also in child templates
it evaluates all files included
Great u guya gonna be envy when i create "new facebook" ;)
Especially @vagrant adder
joke's on you. I've already done it
We rich
@native tide vscode has flask and django debugger support too
but it is really not as extensive
working with pycharm is a whole different level compared to vs code
unfortunately
Alone the breadcrumbs are worth it
Hey, any python web developer willing to hop in a voice chat later to help me with some questions regarding web development with python?
How about you ask them here and if you don't get the answers you're looking for then we can vc ? That way more people would benefit from it
If you're a student @native tide you can get the whole jetbrains suite for free
You are right, basically I'm looking to get into web development with python, I know some Django (created a simple portfolio website that I'm currently still working on) and I'm looking to do some free websites for friends/small businesses to add to my portfolio.
I'm looking for advice on how should I go about this. Should I go with Django or some lighter framework? (I want to start with some basic landing pages, blog type websites)
have you worked with flask before?
Currently I'm learning js and I plan to polish my css and html skills doing these projects
Ive heard about it but never used it
if you're planning to go with basic stuff i would say you should go with flask
django is good for more scalable apps
but if its basic flask is nice
Does it have an admin page like Django? Let's say the user wants to edit some stuff on his own then he can do it himself
nope
reason because its meant to build basic apps
although you can easily build an admin page if you want
also its like very diluted version of django so if you've worked on django before flask will be easy to start with
I heard it's easier to pick up than django
it is indeed
It is lighter and easier to pickup, but I'll throw a vote in for Django because it does have many of the things you might want to later add to a flask app. Yes, you might be including it if you don't need it, but I end up using a lot of that stuff as the app grows.
I have to add that my knowledge to databases its limited, I've only worked with them trough Djangos orm using sq3lite
And having a default admin installed for the ORM is really awesome.
well there are things to lookout that you might add in your app
based on that you can decide which framework to go with
Also what do you mean by "go about this"? Go about learning Django/Flask/etc.?
For know I think I'm going to stick to Django since I know it. Also I'm learning Javascript atm, I don't really want to overwhelm my self with all this
I found that just creating what I wanted to create, while implementing different tools as you go, is really the best way I learned. If I couldn't figure out how to implement what I wanted, I just researched it and kept trying until it worked. That, of course, is figuring that you have at least a solid python understanding.
And by solid I really just mean basic operations.
One more quick thing, is there a Django plugin for blog type websites. I have a blog section on my personal website and the content part is just a text field. I would like to be able to modify the text, add images links etc. Any idea how would I go about doing that?
There are most likely Django libraries that are built to do this. You could literally google for django blog, and probably find what you want.
I feel like I know the basic python stuff. I've also built a couple apps using pyqt5 with some webscraper scripts attached to it, nothing huge tough
There is a really good tutorial, written Django Girls I think, that introduces you to Django by creating a blog.
It was super helpful for me early on.
I have my website up and running just have to mess with the css abit to make it work properly on mobile
Gonna check out the tutorial, thank you
@reef zealot I would like to be able to modify the text, add images links etc. Any idea how would I go about doing that? Look into tinymce / ckeditor / summernote they all have django specific libraries
Thank you BassSpleen
@bleak bobcat Yeah my student days are long gone bro , thnaks either way
https://duckduckgo.com/?q=malicious+npm+package&t=canonical&ia=web @tired root ๐คข
Is the yarn ecosystem any better than npm?
Imagine if in order to make a python app you had to do python3 -m pip install * and there was that historical list of problems with pypi.
Yarn isn't really better than npm - and you can still get npm packages with it
mm
I have a problem regarding 'background-image' which's URL is a page that gets an SVG and fills it with a certain colour - and it doesnt load. The script is in PHP and upon going to the page in the browser the SVG renders perfectly. I was wondering does 'background-image' have some sort of timeout or is my SVG malformed?
CSS:
background-image: url('/api/core/get/image/svg.php?path=/images/icons/material/image/svg/production/ic_image_48px.svg&fill=fff');
SVG (filled):
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48" style="fill: #000; ">
<path d="M42 38V10c0-2.21-1.79-4-4-4H10c-2.21 0-4 1.79-4 4v28c0 2.21 1.79 4 4 4h28c2.21 0 4-1.79 4-4zM17 27l5 6.01L29 24l9 12H10l7-9z"></path>
<style>svg * { fill: inherit !important; }</style>
</svg>
I am confident there is nothing wrong with the PHP script.
**Edit: I did figure out what was wrong. The Content-Type was 'text/html' not 'image/svg+xml' thereby the browser wouldn't accept it.
Do you intentionally have an absolute path from root or should that be a relative path?
I check its a safe path dw and yes, its intentionally absolute
Are you confident its not a permissions problem? If not that I got nothing.
So I am returning this from a request to my server
This is a nested dict of course, I am trying to access the values of Data but I cant
function showdata(){
data = get_data();
console.log(data);
for (i in data['Data']){
console.log(i);
}
}
This only logs the data but not the i
I'm a little torn between thinking that npm is awful and that React is a little fun. It's like knowing that going to the strip club and blowing all your money on cocaine and hookers (I don't do this btw) is probably going to get you a disease, but its probably fun to do. ๐
Either way, I have meetings all day, so no time to play with it
NPM is definitely awful (but I find it much easier to use than anything in the Python ecosystem)
a JS question ...
I have an old system trying to get a user's timezone with geolocation which is a bit problematic for a variety of reasons.
I see now, Intl.DateTimeFormat().resolvedOptions() (and the timeZone attribute) are working pretty well across the board, so I may be able to use that now.
Anyone else getting a user's timezone?Have any problems with Intl recently? or someother reason to still use geolocation?
I don't see why you'd use a service just to get the time zone
yeah I don't see a reason either, but I thought I'd ask to see if anyone has ran into a reason. This app was written about 10 years ago, so there is a lot I am running into that doesn't seem to make much sense anymore.
Thanks for the link, btw, I saw that too, curious if I'd see any difference between the data I get from Date and Intl, presumably not.
Well, Javascript embedded in HTML always runs in the browser
so any date constructed has a local timestamp
The only thing you cannot solve this way, is if the user's pc has a different TZ
but then, I am a big proponent of respecting the users settings
That was probably the rationale behind using a geoip service
to get the real timezone
BUt I say it is a real edge case where people have a different TZ set than they are in
yeah, with the service they chose we were seeing all sorts of issues like their location being across a tz border, vpn issues, and other innaccuracies. I think respecting the user settings is best, there is no reason to try to not trust the user they could always manipulate the results if they really wanted to. It's better for it to be simply explainable "the site shows this because of a setting on your computer, which you can change." I think the oringial intent was to not trust the user but that seems awefully misguided to me.
Anyone know why I am getting this as a request path
but I am using this
<script type="text/javascript" src="{{ url_for('static', filename='js/charts.js)') }}"></script>
in flask if decorate a handler with @app.errorhandler(SomeException) why is it still throwing the exception? how do I catch it?
def handle_expired_error(ex):
response = jsonify({
'message': 'Token has expired'
})
response.status_code = 401
logger.info(f'{ex}')
return response```
hi guys i want to ask how to extend(modify) django database backend
@dusky osprey why dont you just do a normal try except block
@shadow rock where should I put it? that exception is thrown each time a jwt token is expired
which jwt library are you using
flask_jwt_extended
from flask_jwt_extended import JWTManager
jwt = JWTManager(app)
@jwt.expired_token_loader
def expred_token_callback():
return {"msg": "EXPIRED_TOKEN"}, 401
this assumes you're just flask-restful so you dont have to jsonify
but if you are not using that library, just go ahead ahead jsonify
You don't need to jsonify in normal flask either
oh really? i thought you had to
I think in one of the relatively recent updates they made it so you don't need to
cool
@shadow rock btw if you are implementing this for sensitive data, dont use flask's JWT, try out authlib
@rustic pebble authlib seems like a library to help implementing oauth
and depending on how your auth is set up, you may still end up using jwts
search for authlib jose
that's what im saying, you use oauth to connect to a provider and make sure the user is authorized, and then your server still sends back a jwt in which authlib will handle
devs shouldn't use this library if they're just strictly doing jwt and auth themselves
its a lot of library for a simple process
hey im new in this server, does anyone know why i am getting this message with flask even though i have set a secret key?
sorry if im interrupting something but i have an urgent project and im a bit of a noob with this
andim trying to get all the help possible
show you flask configurations
it should look like this
app = Flask(__name__)
load_dotenv(".env")
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("DATABASE_URL")
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["PROPAGATE_EXCEPTIONS"] = True
app.config["JWT_BLACKLIST_ENABLED"] = True
app.config["JWT_BLACKLIST_TOKEN_CHECKS"] = [
"access",
"refresh",
]
app.config["CELERY_BROKER_URL"] = "redis://localhost:6379/0"
app.config["CELERY_RESULT_BACKEND"] = "redis://localhost:6379/0"
app.secret_key = os.environ.get("APP_SECRET_KEY")
api = Api(app)
jwt = JWTManager(app)
cors = CORS(app)
migrate = Migrate(app, db)
look something* like this
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)
if __name__ == '__main__':
app.secret_key = "thisisasecretkey"
app.run(debug=True)
API_KEY = 'fb84b8439094cc9d7a227150da1474d8'
API_SECRET = 'f25d18ad01e64c9887b5ca312f502787'
network = pylast.LastFMNetwork(api_key=API_KEY, api_secret=API_SECRET,)
block out the spotify stuffs
you just released spotify information into the open
edit your message to do this
oopslol
SPOTIPY_CLIENT_ID=''
SPOTIPY_CLIENT_SECRET=''
SPOTIPY_REDIRECT_URI=''
alright
first off, you may wanna search up environment variables
to take care of that later
but also try this
app = Flask(__name__)
app.secret_key = "thisisasecretkey"
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)
if __name__ == '__main__':
app.run(debug=True)
API_KEY = 'fb84b8439094cc9d7a227150da1474d8'
API_SECRET = 'f25d18ad01e64c9887b5ca312f502787'
network = pylast.LastFMNetwork(api_key=API_KEY, api_secret=API_SECRET,)
i'm assumign this just a toy project, but if you're going into production with this make sure you change your API_KEY, API_SECRET
ok that worked thank you, this is a college project i dont give a shit about so yeah
but much appreciated
np
Can someone explain what feels like a missing link in the Braintree setup for me? I understand that a customer_id is used to get a client_token, but nowhere can I find an explanation of how/why this works to make one.
I see docs about needing it and what the object looks like but like... if the buyer is buying something, do they have to create some kind of account for this id? Do I take it from their user account, therefore requiring all those values like first/last name, address, etc. when they signup on my website and then create it on their behalf? Could really use some clarification on this logic.
@shadow rock I think there's a bug, actually I use both @jwt.expired_token_loader and @app.errorhandler but sentry is still reporting the exception
are you using flask_restful or flask_rest_plus
Flask-RESTful==0.3.6
What are good Django or Backend Projects Ideas for Beginners looking to build a portfolio?
I would guess anything that involved users logging in, having accounts they can change options in, and ways they can do things and have separate data thats all kept and normalized well.
I'm not an expert in this, but that's what my first thing was. Its a microblog that's only purpose is to show I can validate accounts, send out emails to change passwords. I imagine you could go further with some ways of storing payment methods and adding people to news letters.
If its for a portfolio, that sort of thing makes sense to me. But again, this is just my thinking. It not an experts.
@glossy atlas Learn django until you really know it, then look for projects to contribute to, on Github with your real name. That is how you get best attention
An employer would google your name and find you active on Github
When I was in the market for a new job, the employer actually printed out source code of mine and asked me to explain what it does during the interview
Even though I am a Sysadmin/Network Administrator and not a programmer
but he wanted to know if I am bullshitting or not
@tired root So, If I feel confident enough (By following and copying enough tutorials) all I need to do to get started with real projects is to find a GitHub Django project that's open and in progress and work on it?
Yeah. Find something you find interesting and submit pull requests, fix bugs etc.
But don't submit bullshit
Many do that to fill their activity page
Contributing to FOSS is something professional employers value a lot
@tired root Define "submit". What do you mean by that exactly?
sending pull requests
when you do a git push that is a pull request for the maintainer
@tired root Oh, I get what you mean. Sounds like a better idea. I got tired of "Tutorial Hell"
I mean, I've learned flask by making a radio station out my pi
It's not yet fully done, but usable
Maybe find something you need to deepen your knowledge
@tired root Well, I like Statistics and Web Development so I would like to do something like this:
https://www.freecodecamp.org/news/how-to-create-an-analytics-dashboard-in-django-app/ at some point.
@tired root The analytics project is too advanced for me (I think) but thank you for pointing me in a direction! ๐
Is there anyway in Jinja2 to do {% if now-timestamp > 30 %} ? now is the current timestamp and timestamp is a timestamp from a database. I can't seem to do a greater than sybmol and a calculation at the same point. Any help?
Is there a way to have default selections for a select without adding a selected to it
Cause i dont want to have duplicates
@fossil swift that code as written "works" for me--crashes because timestamp deltas are not integers so there's a typeerror
You might want to try (now - last).total_seconds() > 30
I have a json file in this format:
{ date: { country: {'confirmed':, 'deaths':, 'recovered':}}}
I want to iterate in js through each of the countries
can you paste slightly more of the format? e.g 2/3 countries
can you pastebin it so its easier to read?
eh top 500
This just spits out the total data for each day
async function global_numbers() {
let data = await get_data();
await console.log(data);
count = 0;
for (date in data) {
count += 1;
await console.log(data[date][0]);
}
await console.log(count);
}
But I cant get it to work for each country
Isn't this Python server?
Oh
@rustic pebble
const jsonString = `{
"01-22-2020": [
{
"Mainland China": {
"ConfirmedCases": 547,
"Deaths": 17,
"Recovered": 28
},
"Hong Kong": {
"ConfirmedCases": 0,
"Deaths": 0,
"Recovered": 0
},
"Macau": {
"ConfirmedCases": 1,
"Deaths": 0,
"Recovered": 0
},
"Taiwan": {
"ConfirmedCases": 1,
"Deaths": 0,
"Recovered": 0
},
"US": {
"ConfirmedCases": 1,
"Deaths": 0,
"Recovered": 0
},
"Japan": {
"ConfirmedCases": 2,
"Deaths": 0,
"Recovered": 0
},
"Thailand": {
"ConfirmedCases": 2,
"Deaths": 0,
"Recovered": 0
},
"South Korea": {
"ConfirmedCases": 1,
"Deaths": 0,
"Recovered": 0
}
}
]}`
let parsed = JSON.parse(jsonString)
console.log(parsed)
for (let [date, countries] of Object.entries(parsed)) {
for (let [countryName, value] of Object.entries(countries[0])) {
console.log(countryName)
}
}
@rigid laurel the dict that gets returned is returned using this:
return await response.json()
Do I have to use JSON.parse again?
no, you'd just use the result of that
it might be slightly different for your object
but I'm pretty sure the use of object.entries is the solution
In my case, which is a json reply from the server, what should I set the parsed as
so I assume you have something like ```js
const myObj = fetch(stuff)
if so, you just want to use `myObj` as parsed
I have this:
async function get_data(){
let url = '/totaldata';
const response = await fetch(url, {
method: 'GET',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
});
let data = await response.json();
return data['Data']}
This is the flask backend
@app.route('/totaldata', methods=['GET'])
def totaldata():
with open('totaldata.json', 'r') as file:
jsfile = json.load(file)
response = {'Success':'Data has been successfully obtained', 'Data': jsfile}
return response, 200
jsfile is jsonfile
so you'd replace parsed with the result of get_data() I think
Right, that is what I thought from the start
let me try and I will update, thanks a ton!
I have only tested it with the sample I posted above, so there might be issues with translating it to the big json
So it works haha
If I wanted to access the keys inside each country name?
Would I have to open one more loop with the scheme of the previous?
for (let [countryName, value] of Object.entries(countries[0])) {
console.log(countryName)
console.log(value.confirmedDeaths)
}```
You. Are. God.
I have a question tho, how does it translate say deaths which is a key to an attribute?
let [countryName, value] of Object.entries(whatever) is the exact same as doing for k, v in my_dict.items() in python, except instead of being a dict its a JS object
ooh
I am not really good with JS, I mostly use it to pass requests from/to server and just change elements
and with js objects, you can do both my_object.key, and my_object[key]
Thats the main thing you want to do with JS - its great for element manipulation, absolutely miserable for data manipulation
I have got that impression from the moment I started using it for data manipulation
But I really dont like loading the server with unneeded things
I have nightmares of NaN appearing everywhere
yeah, showing NaN and undefined to the user is rubbish
Overall JS is nice, but it gives me PTSD every time I use it to parse data from the server
Btw what is the equivalent of dictname.update() in js?
Oh nvm found it, it is push
what size of image should i use for css bc everytime i use an image it becomes blurry
and i heard that if u find a larger image it will be clear
for what?
for my website
for what on your website?
the background image
Generally you want images to be as high resolution as possible
for a background you probably want it to look good on most screens which means 1920x1080 at least
sounds to me like its due to the order in which you're loading things
but I could be wrong
* {
margin: 0;
padding: 0;
}
header {
background-image: url("startup-593327_1920.jpg");
height: 100vh;
background-size: cover;
background-position: center;
}
.main-nav {
float: right;
list-style: none;
margin-top: 30px;
}
.main-nav li {
display: inline-block;
}
.main-nav li a {
color: white;
text-decoration: none;
padding: 5px 20px;
font-family: "Roboto", "sans-serif";
font-size: 15px;
}```
my code wont show the nav bar
it still shows as the list on the left
Hey guys, I am currently fetching some data from an API and I would like to use the data in a function, but I dont want to run the function inside the fetch() success part, I want to run the function in the main javascript body.
Is there anyway I can do that?
My example Code:
fetch("/api/test/", {method: "get"})
.then(function(response) {
return response.json();
})
.then(function(data) {
//success
console.log(data);
})
.catch(function(ex) {
console.log("parsing failed", ex);
});
function somefunc(data){
console.log(data);
}
// run function here
so you want to be able to do something like
myData = fetchData(url)
processData(myData)
```? @tranquil robin
yes
Has anyone ever used chartjs?
I am trying to create a multiline chart and I am getting a weird glitch
I tried using chartjs, but it wasnt very flexible so I moved to am4charts ๐
@native tide Are you using flask?
There is flask-minify for template output
otherwise there is uglifyjs and uglifycss on npm to use
hi flask friends
Hello, if I want to build a Django web app that scrapes other websites with the data entered by the user, how would I go about this? I make the script, implement it in my Django app and when user clicks a button Django runs it?
@reef zealot you would probably have a page with a form to request the relevant input from the user, and on submitting the form, you would use the input in your script
Yeah, but how will Django handle the script? Does it have to be async? Could I implement the script to run from the client side?
I'll explain what I'm trying to do here, I want to create a web app that searches for AWBs on different courier sites and the user can simply enter whatever awb he wants and would get the result
Running the script from the web app might get the IP blacklisted
@reef zealot You can implement the script to run client side but youwill need javascript for that. Optimally you shouldn't make it async as Django already has a response management system which takes care of multiprocessing
You should treat each connection as a seperate instance of your server
Hmm thank you for the information, I'll just go at it in the weekend and see where I get
Sure
Guys
Should I use django or flask?
(Not a beginner though)
And I've used both
What usecase
^^^
Like for making an online shop
For an online shop id lean towards Django. You probably are gonna end up wanting most of the main features
Yes, django is serve you better
Google is always complaining about my footer, for elements being too close together on mobile. While this snaps into a 1 column on mobile, I am not really sure what to do about it. Any ideas?
What does it look like on mobile ?
Google probably wants you to increase the vertical margin between elements
Imagine a fat finger, is there a chance it can click on 2 elements at the same time ?
Yea, links are just too close to each others
hi guys
i need to modify django.db.backends.utils.py CursorDebugWrapper but how do i apply it to the entire project?
I honestly don't know @tired root it's been a while since I've had time to have fun with frontend
Is flask login server or client side?
@limber laurel server side ofc
Has anybody used ChartJS I am having a problem displaying the correct labels in a line chart
Ok danke
Firebase storage? It looks like a cdn, so it is built for that @ashen trench
yeah'
Yes, it is a cdn, it is built to serve statics
Firebase storage is essentially like S# buckets
S3*
But there is nothing much on it online for django if we look into s3 integration there is a lot of doc within the django official site
All i want is to serve my static files and media files with the firebase while my code is hosted on EC2
I mean, firebase isn't that used from what I saw, but you can just make a little script that uploads your statics to your firebase, put it under a cdn. subdomain, and use it inside your html, and you're golden
I am literally getting trolled by javascript
The set is having multiple values
but only 3 get on the diagram
wtd
i know its outdates and they got an API out but i really wanted to finish this
i am making a twitter bot and having it just like a bunch every now and then i have come a good bit but cant make it work how it should even after using a bunch of methods (lost most solotions) but this is waht i got so far
## first beta
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
import time
##
class TwitterBot:
def __init__(self,username,password):
self.username = username
self.password = password
self.bot = webdriver.Firefox()
def login(self):
bot = self.bot
bot.get('https://twitter.com/login')
time.sleep(3)
email = bot.find_element_by_name('session[username_or_email]')
password = bot.find_element_by_name('session[password]')
email.clear()
password.clear()
email.send_keys(self.username)
password.send_keys(self.password)
password.send_keys(Keys.RETURN)
time.sleep(3)
def like_tweet(self, hashtag):
bot = self.bot
bot.get('https://twitter.com/search?q='+hashtag)
time.sleep(2)
for i in range(1,3):
bot.execute_script('window.scrollTo(0,document.body.scrollHeight);')
time.sleep(2)
tweets = bot.find_elements_by_class_name('tweet')
links = [elem.get_attribute('data-permalink-path') for elem in tweets]
print(links)
for link in links:
bot.get('https://twitter.com' + link)
try:
bot.find_element_by_class_name('HeartAnimation').click()
time.sleep(10)
except Exeption as ex:
time.sleep(60)
ed = TwitterBot('xxxxxxxxxxxxxxxxxxxxxx', 'xxxxxxxxxxxxxxxxxxx')
ed.login()
ed.like_tweet('webdevelopment')
time.sleep(3)
the login function is fine untill half way of the like_tweet function
Twitter has an API
Your life will be much easier if you use it
There are even Python libraries for it
Oh you acknowledged that
Regardless, the way you're doing it is against their ToS and thus against this server's rules
Using the API wouldn't be
Does anyone have experience how to set up subdomains using Flask and Heroku?
.flaskenv
# ...
SERVER_NAME=myappname.herokuapp.com
# Have also tried SERVER_NAME=mydomain.com
#...
@app.route('/', subdomain='sub', methods=['GET', 'POST'])
I have enabled:
heroku domains:add *.mydomain.com
Have added CNAME/ALIAS as such:
Host Record: sub
Points to: mydnstarget.herokudns.com
TTL: 14400
Still, I can't access sub.mydomain.com or sub.myappname.herokuapp.com It doesn't redirect to the desired route as I've specified in routes.py. Returns my endpoint for 404: @app.errorhandler(404).
Guys I'm having an issue with django
urls.pyfrom django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.urls import path from . import views app_name = 'blog' urlpatterns = [ #... static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT), ]AUTH_USER_MODEL = "blog.User" MEDIA_URL = "/uploads/" MEDIA_ROOT = os.path.join(BASE_DIR, "uploads")ERROR
?: (urls.E004) Your URL pattern [<URLPattern '^uploads/(?P<path>.*)$'>] is invalid. Ensure that urlpatterns is a list of pa th() and/or re_path() instances.@native tide you should not include static inside the urlpatterns like above, it won't work.
but you can add your static files to urlpatterns like this:
urlpatterns = [] + static()
this is the correct way
I enjoy
dev_server_urls = [static(settings.STATIC_URL, document_root=settings.STATIC_ROOT),
static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)]
if settings.DEBUG:
for static_url in dev_server_urls:
urlpatterns += static_url
I have a question about User accounts that have two different profiles for options. Should I make a model of a base user class inheriting AbstractUser?
Django obviously
Or should I just use the one included?
The main thing that is not accepable about the default User is that there is no BooleanField for password confirmed in email, or... email must be unique in database
Which is just unacceptable
So I answered my own question. But what do you typically inherit User or AbstractUser ?
So Im reading that its considered best practice to write a new user class in the beginning by default in any Django project.
I'm having trouble saving my secret key as an environment variable. I cant even get bash to echo it out
if I do DJANGO_SECRET_KEY="<insert-key>" where <insert-key> is the key, I get bash: !8: event not found which I assume has to do with some escapings in the string. I get the same thing where I try to echo it as string literal or anything else.
I'm having so many problems this morning Im just going to sleep on them. I'll get to the next problems after I give time to hear back on this one
Hey, I'm building a REST API and I'm wondering how I should authenticate if user is allowed to use X api feature.
Currently I'm saving the hashed versions of passwords in database and when Im making a request I'm comparing the plain password to the databases hashed version.
Example: I'm sending a POST request to http://127.0.0.1:5000/customer to add new customer to db. The POST request would include the customer's information and the sender's user and password. All this in JSON. What I'm asking if this is a good way to handle this or should I do it some other way? I'm using Flask.
I was mistaken to think that I was ready to move on from Django. I'm getting stuck at some pretty basic things on my own project, with nothing to help me..
users/models.py
from django.contrib.auth.models import AbstractBaseUser
class User(AbstractBaseUser):
"""
Account Holding Base User
"""
email = models.EmailField(max_length=50, unique=True)
date_of_birth = models.DateField()
created_on = DateTimeField(timezone.now())
email_verified = models.BooleanField(default=False)
game_master_switch = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
EMAIL_FIELD = 'email'
REQUIRED_FIELDS = ['date_of_birth']
the errors are too long for copypasta https://paste.pythondiscord.com/usexubogen.py
it definitely had to do with... I need to inherit all the things that AbstractBaseUser has into my User that I'm not specifying, because if you read that class, it has everything being said is missing.
I have question about FastAPI: Is possible to generate JWT key in shell, due I don't want register and login endpoints, due it's private API? Like in Django createsuperuser?
You could just make a custom entry point that generates a token, print it to stdout and exit
ok
But I have to find way how can discord.py bot and fastapi communicate on startup for key (in different servers).
But is good idea (security) to manually generate token and add this to bot and api .env file?
It should be fine as long you aren't working for the NSA
No, discord pokemon bot...
Should be fine then
I'm trying to use Flask to build an API so that I can send and receive requests between a server script and multiple client scripts. However I'm unsure how to do this.
from flask import Flask
server = Flask(__name__)
@server.route("/")
def connection():
return "Connected"
if __name__ == '__main__':
server.run(debug=True)```
This is my server code for testing
I want to create a client that can receive and print the "Connected" string
Thank you ๐
The client will simply have to use a GET request on the root url
If you are running it on your computer atm, it should be http://127.0.0.1:8000
How would I go about coding that in a client.py file?
Sorry if this is a dumb question, I'm completely new to using Flask and can't seem to find any solutions for this online
You can't use flask for that
Flask is just a way to create the server not the client
You'd have to use another library such as requests
!d requests
This part of the documentation covers all the interfaces of Requests. For parts where Requests depends on external libraries, we document the most important right here and provide links to the canonical documentation.
Okay thank you ๐
So, just to clarify, use Flask to make the server and then requests to make the client?
Flask to make the server, requests to interact with it
Hey guys! Any ideas (+ maybe code examples) on how to deploy a Flask-Socketio app with docker?
Is there a connection protocol supported by a python library, which combines the "all-the-time connected" attribute of websockets with the "1 response to 1 request" structure from http?
what's the name of the {โ
โ
} markup you use in templates?
I'm trying to Google a thing but I don't know what to call it
ok I think I maybe found the name. jinja2?
Hey there, im a total noob so here comes a noob question: how i make this line to work
self.driver.find_element_by_name('password').send_keys(Keys.CONTROL + Keys.SHIFT + M)
i can send solo key signals
but i cant send them as a combo
and keys.m doesnt exist
so m is a string wich is m
yep
i want that a webpage goes intro phone mode
if u go on chrome, press control + shift + m it goes in that mode
but im not sure how to do that in code
brb need to get something
@ruby palm sry going to be afk for about 30 min
How do I pass a variable through a Flask subroutine?
gameID = 0
games = []
players = ["Player"]
@server.route("/newGame")
def newGame():
#Getting an error about gameID being referenced before assignment here
Temp = game(gameID, players)
games.append(Temp)
gameID += 1
return Temp.getGameID()```
How would I go about doing that?
What exactly would want to pass into it?
The global variable gameID above
gimme a sec
Nw, thank you
from flask import g
g.gameid = 0 # can set this wherever or however you like
g.games = []
players = ["Player"]
@server.route("/newGame")
def newGame():
#Getting an error about gameID being referenced before assignment here
Temp = game(g.gameid, players)
g.games.append(Temp)
g.gameid+= 1
return Temp.getGameID()
something roughly like that
There's the docs for that bit
Perfect, thank you
Oh, I missed a bit out. players should become g.players
Yeah, don't worry about it aha
Thanks a lot, that's amazing ๐
Traceback (most recent call last):
File "Server.py", line 159, in <module>
g.gameID = 0
File "Python\Python38-32\lib\site-packages\werkzeug\local.py", line 364, in <lambda>
__setattr__ = lambda x, n, v: setattr(x._get_current_object(), n, v)
File "Python\Python38-32\lib\site-packages\werkzeug\local.py", line 306, in _get_current_object
return self.__local()
File "Python\Python38-32\lib\site-packages\flask\globals.py", line 45, in _lookup_app_object
raise RuntimeError(_app_ctx_err_msg)
RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this, set up an application context with app.app_context(). See the
documentation for more information.```
Any idea what that's about?
OH I missed
something
def create_app():
app = Flask(__name__)
with app.app_context():
g.gameid = 0 # can set this wherever or however you like
g.games = []
g.players = ["Player"]
return app
You need to put that somewhere
and the somewhere will depend on exactly how you're running your code at the moment I think
Yes
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
from flask import Flask
from flask import g
server = Flask(__name__)
g.gameID = 0
g.games = []
g.players = ["Player"]
@server.route("/")
def connection():
return "Welcome to BlackJack"
@server.route("/newGame")
def newGame():
Temp = game(g.gameID, g.players)
g.games.append(Temp)
g.gameID += 1
return Temp.getGameID()
if __name__ == '__main__':
server.run(debug=True)```
That's all the Flask code I have rn
replace your server = with server = create_app()
also, app is the standard name for what you currently have called server
Okay yeah, is it worth changing to app?
At this point it is yeah
Okay
if you need help in the future, it will make the helpers life easier
Got it
from flask import Flask
from flask import g
def create_app():
app = Flask(__name__)
with app.app_context():
g.gameID = 0
g.games = []
g.players = ["Player"]
return app
app = create_app()
@app.route("/")
def connection():
return "Welcome to BlackJack"
@app.route("/newGame")
def newGame():
Temp = game(g.gameID, g.players)
g.games.append(Temp)
g.gameID += 1
return Temp.getGameID()
if __name__ == '__main__':
app.run(debug=True)```
So should have this?
from flask import Flask
from flask import g
def create_app():
app = Flask(__name__)
with app.app_context():
g.gameid = 0 # can set this wherever or however you like
g.games = []
g.players = ["Player"]
return app
@app.route("/")
def connection():
return "Welcome to BlackJack"
@app.route("/newGame")
def newGame():
Temp = game(g.gameID, g.players)
g.games.append(Temp)
g.gameID += 1
return Temp.getGameID()
if __name__ == '__main__':
app = create_app()
app.run(debug=True)
Getting an error of "app" not being defined on the line "@app.route("/")"
I'm trying to figure out the right way to do it
I've done this before and it wasn't difficult
ahh - the way I told you to do it isn't the way I've done it before. This should work
from flask import Flask
from flask import g
app = Flask(__name__)
@app.before_request
def before_request():
g.gameID = 0 # can set this wherever or however you like
g.games = ['fasd']
g.players = ["Player"]
@app.route("/")
def connection():
return "Welcome to BlackJack"
@app.route("/newGame")
def newGame():
Temp = game(g.gameID, g.players)
g.games.append(Temp)
g.gameID += 1
return Temp.getGameID()
if __name__ == '__main__':
app.run(debug=True)
A trimmed down version of that runs for me
Works now
Thanks so much
Can't return integers for some reason though
Had to change one of the lines to "return str(Temp.getGameID())"
So I didn't really think about what you were doing til now. The globals will run for this without error, but I don't think it will do what you want. If you want to store data between multiple requests (which it seems you do), then you need to store that in some other wayy. The standard way would be with a session, with a database, or with some kind of cache like redis
The easiest one of those is with a session
How easy is it to make a session?
Not too difficult, its a very similar idea to the g thing
flask-session is the normal way
Oh wait
there's a session object in flask
Do u know how to use it?
[FLASK]
Does anybody knows how can point my 'static' folder to an URL endpoint that doesn't match my app SERVER_NAME? My app runs on Heroku.
Domain: mydomain.com
HerokuServer: my.herokuapp.com
Flask SERVER_NAME is set to mydomain.com in order to build subdomains such as sub.mydomain.com. My domain is set an ALIAS/CNAME to point * .mydomain.com to my.herokudns.com.
But, because of that, when I use url_for('static') it's trying to search files on my.domain.com instead of my.herokuapp.com.
Can anybody help me on that?
im deploying my flask app to heroku
it builds sucessfully
but when I go to the link it says its broken
anyone want to look at my procfile/requirements/runtime/aptfile
runetime.txt: python-3.8.2
Procfile:
worker: set FLASK_APP=app.py
flask run
probably wrong^
Aptfile: git
requirements.txt: git+git://github.com/lovvskillz/python-discord-webhook.git
please ping me when someone responds
@weary acorn remove that flask run
and send me scrnshot of Logs of heroku
I dont have the heroku cli
is your bot online?
I doing it through the website
no
i try to upload it
it says its deployes
but when I go to the link
ohkk i will help you
is your bot running perfectly in ur system
yep
install heroku cli
how
you're using windows?
yep
download it
and install
open command prompt as admin
make new app in heroku dashboard https://dashboard.heroku.com/
i have
ohkk
yes
ok but I dont have mic
i also will not speak too
ok
ok
class User(AbstractUser):
"""
Account Holding Base User
"""
email = models.EmailField(max_length=50, unique=True)
date_of_birth = models.DateField()
created_on = DateTimeField(timezone.now())
email_verified = models.BooleanField(default=False)
game_master_switch = models.BooleanField(default=False) # TODO: True to Designate a GameMasterProfile
USERNAME_FIELD = 'email'
EMAIL_FIELD = 'email'
REQUIRED_FIELDS = ['date_of_birth']
def create_superuser(self, email=None, password=None):
user = self.create_user(
email=email,
password=password,
is_staff=True,
is_admin=True
)
return user
after making these migrations, I try to createsuperuser
I get though asking for email, dob, password, but I always get this
File "Projects/shell_hacker_game/venv/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 189, in handle
self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
TypeError: create_superuser() missing 1 required positional argument: 'username'
I dont need a username. An email is all I need.
I can only assume its referring to a method defined somewhere else
Man, I'm getting tired of Django tbh
Everything that you do in this framework is writing over something else and there is no joy in it.
I'm sure that it gets products out quickly.
I'm losing interest in digging in these docs in my spare time to change default functionality though
I could feasibly make the username = the email in the code but then Im keeping duplicate data because im tired of digging in Django code lol
I think what I have to do is create AbstractBaseUser instead of just AbstractUser but I have to do a lot of copying the default and only changing it where I want.
https://cdn.discordapp.com/attachments/303906556754395136/688630946764947496/redirect_problem.mp4
why the redirect isn't working properly
Random question but does anyone know of a good guide for implementing a rest client? But not just an example tutorial where they make one request but like an enterprise level system design guide?
I may very likely throw my django project in the trash and start on flask.
Just to see how it might be different than this.
Using django, trying to make a website, part of which allows users to submit text to be displayed. Problem: I obviously don't trust my users, so I want django's autoescape, however I do want them to be able to insert new lines. When I just do .replace('\n', '<br>') on their input, django escapes the <br> and displays it literally. How can I change that?
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Hi, I'm trying to create a multiplayer blackjack game with a server that can connect with multiple clients so that they can play against each other.
As of now, I have created a local one player game and am attempting to use Flask and Requests to rewrite the code into a client and server script.
However I'm unsure of where to start with this as I'm very new to using the Flask library.
All help is really appreciated, thank you ๐
@agile wave you should probably use a socket based library
I've tried but the ones I've found are too low level to be useful
Wdym?
I've had to spend ages coming up with my own header system and I needed to make sure that both scripts were receiving/sending the required data at the same time and it was too easy for them to go out of sync
With Flask, I can see that I'll be able to send a request and then get something back based entirely on that since it's stateless
Yes but opening sessions with flask isnt as easy
What would you suggest?
I just feel like it's too much work to set that up for what it does
Is there not an easier way to just send variables between programs over the internet?
you are looking for a socket
I've used sockets, there's too much overhead and it doesn't do what I actually want it to do
I need my client to send something to the server, then the server runs a function based on what was sent
Sockets just take what was sent as a variable and I can't see a way to use that to call different functions without almost creating my own library
is it possible to capture the client's webcam on send over to python using flask/socket.io?
@green echo I gues
guess*
But you need to use javascript for that, and use sockets not flask
yeah sure
ok now for the question
is it possible how to capture the client's webcam on send over to python using flask/socket.io? javascript and sockets?
@rustic pebble ?
Not really sure how you would pass it to the server-side, aiohttp should be the way to go
then what is the problem?
passing it to the server side
i want it to pass the frames like
in a perfect world example:
send_server(video.read())
But this is getting me nervous because an aspect of my project has this
actually 2 aspects
If I were you I would find any way I could and then just make a module out of it so I can actually just do send_server(video.read())
I am not sure you would want to build it with python backend at all
Look up feathers.js
im creating a web app using django
but how to save the webcam pics and upload it to the database?
<input type="file" accept="image/*" capture="camera"> this doesnt work for pc!
@dense mica you realize your question is the about the same as the question i asked right before you
yeah
hey i have link
but it is written in spanish and hard to understand
okie
the codes written in spanish*
lmao wat
all i need to know is how to send an image from webcam to python using sockets
Hi can anyone help me locate an XPath with Selenium based on a td ?
This doesn't seem to work
driver.find_element_by_xpath("/html/body/div/main/div[2]/div[1]/div[2]/div[3]/table/tbody/tr[2]/td[text()='Rachel']/button")
@wicked basalt what's the website and element
It's a private website but it looks like this :
Is the button you want to click
Text identifiable?
I mean, I can see that the tr, td and button classes are the same across the application
So you can't identify one from the other based on the class
Can you do it by the text within?
If you can, you can try something like:
driver.find_element_by_xpath("//button[text()[contains(.,'some string')]]")
driver.find_element_by_xpath("//button[text()='some string']")
If the text is not within the button stuff, you have to match it to the element that has it and then continue your search using a ////
driver.find_element_by_xpath("//tr[text()='some string']/button") or something like it
hi there
I was wondering what the top discords/irc's are for getting django help?
please ping me when you reply
@sly canyon Yes, I would like to click on the button that has in td "!Women Art Revolution" for example
Try the options above until you get the right element
Make small adjustments if neccessary
And yes the text is not within the button stuff, so I have to match it to the elment that has it
What's the difference between / and // ?
I tried driver.find_element_by_xpath("//tr[text()='some string'] but I get the NoSuchElementException error ๐ฆ
@wicked basalt you have to make adjustments
Only you have access to the DOM
'some string' has to be replaces
*replaced
that's why it's called 'some string'
Yes I did replace it with "!Women Art Revolution - A Secret History"
But it didn't detectyi t
I think one of the problems is that the button and the td are in the same hierarchy
@wicked basalt so driver.find_element_by_xpath("//tr[text()[contains(.,'!Women Art Revolution - A Secret History')] is not working?
when you use text() = it will only work if the text is exactly equal.
I just tried and it does not work :/
again*
And I put an implicit wait in case too
Anybody know why I am getting import errors in my flask app?
This is my file structure
This is the Idea class
from main import db
class Idea(db.Model):
__tablename__ = "ideas"
id = db.Column(db.Integer, primary_key=True)
title= db.Column(db.String())
post_body = db.Column(db.String())
author = db.Column(db.String())
def __init__(self, title: str, post_body: str, author: str):
self.title = title
self.post_body = post_body
self.author = author
def initiate(self):
db.create_all()
@rustic pebble Have you initialized the DB? db = SQLAlchemy(app)
Paste the first lines of your main.py
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
from controllers.database import Idea
from helpers.user_post import Post
app = Flask(__name__)
from controllers.database import Idea
Ah
ok sec
And let's see what happens
ok
I usually import the db classes after the app has been initialized
Example:
from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_moment import Moment
from flask_babel import Babel
import datetime
from config import Config
# Deploy
app = Flask(__name__, host_matching=True, static_host='maxiimoveis.herokuapp.com')
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
moment = Moment(app)
babel = Babel(app)
from app import routes, models, forms, email, errors, logs, contact
let me try again then
Same error
That's because if I try to import it before instantiating the app, it doesn't work