#web-development
2 messages ยท Page 90 of 1
Hi all
DATETIMES and TIMEZONES. What the hell.
I am building a chat feature into a website and currently all of the users are on one timezone but if it starts getting users from a different timezone will that mess up the time stamps of the message if the time stamps are timezone naive?
Wondering if the solution would be to have timestamp timezone as UTC and then asking the user to give their timezone to do the conversion. Help please ๐
most systems store time in UTC then convert
@zealous siren Thanks so I will have to get timezones from the user
I believe you can with Javascript
Aw okay thanks for that. I will look into it.
@tepid stirrup I'd go with datetime.utcnow() to register everything. you can format times according to the user's location using other tools.
moment.js, pendulum, ....
are there any good python library for manipulating the DOM, or do I have to use javascript for that?
I'm trying to figure out just how full-stack I can get with Python
if you are trying to make a modern site, backend only with python
Frontend will be mostly to all JS/TS
.....well fuck
@vale orbit I feel the same
Guess I cannot put off learning JS any longer then
from what I understand, TS isn't nearly as cancerous as JS, so I guess there's that?
but it's an evil we have to deal with
I hate JS, but not nearly as much as I hate Java
never tried, probably never will.
remember when Java was all about making OOP faster and more effective?
I remember. It has been a long time since then.
but I digress
it did when it came out
@sly canyon Thanks! How does that work with dates and times set by the user just for future ref
JS has nothing to do with Java, thankfully
but like many legacy stuff, it aged poorly
EC6 was just trying to make a name that would catch
It was rushed.
They were like "we need to get this language out now, even if it barely works"
yea, but getting offtopic, point is, good frontends will be Javascript frontends
look into React/Vue/Angular
Ok, so over-under on Svelte JS?
@tepid stirrup you can request.remote_addr and do some GeoIP to guess their location/timezone
edug, that's just delaying doing proper thing
@sly canyon What I mean is like if they wanted to make a start and end time for a task but it was a planner or something like that.
@tepid stirrup if you're using flask https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xii-dates-and-times
If not try "Django moment" on google
@tepid stirrup if you're using flask https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xii-dates-and-times
If not try "Django moment" on google
@sly canyon Thanks I will do
re: Flask routing - is there anything inherently wrong with combining get and post endpoints in the same entry, or should I create an @app.route() for each?
nothing wrong in my POV, sometimes even necessary for me to avoid argparsing
@sly canyon could I perhaps have you take a look at my example and get your feedback on why it might be causing a 500 error?
just a tic
@sly canyon https://pastebin.com/cyAnXFgX
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
additionally, you can ping it yourself at http://zero-25.com
both get and post return 500, and nothing of any use is getting logged
you don't need if request.method == 'GET': 'cause thats the default behavior
oh. I wasn't sure how to differentiate - guess I should've read the docs more thoroughly, haha.
that said - it does work... most of the time.
but for reasons I can't quite figure (which is why Im here) after a while, it stops working and just returns 500.
I'm really not sure why that is
the logs only show WSGI errors with the queries being executed
maybe something related to your databse
well, I thought the same at first two. its just a standard local only mysql. but when I mysql console, it executes queries just fine.
I was however curious about the request object. perhaps Im expecting the wrong behavior from it?
does the internal error happens on local env or only in production?~~~~
its a personal project, so Ive just been tinkering with it on production (I know, bad form)
thatn that's probably why
you're expecting the production server to access stuff that are not there
your local db is not in the production server, most probably
oh no, Im sorry
as soon as you query something, it fails to find it
when I say local only - I meant - closed off from external connection. it's "local" to the app.
thats my mistake.
so you're seeing internal server error on localhost?
yessir
what does the debugger says
if I reset apache2, it goes away for a while
1 sec, I'll show you
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
yeah, really not sure
dang. well, thank you for your time in any case.
guys
i cant create db file for some reason
from flask_login import LoginManager, UserMixin, current_user
from flask_login import logout_user, login_required, login_user
import sqlite3
from flask_sqlalchemy import SQLAlchemy, request, Model
app = Flask(__name__)
app.config['SECRET_KEY'] ='ASSJHADCHASLFDLAKJKkjk;xsjd'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/users.db'
db = SQLAlchemy(app)
class User(db.Model):
__bind_key__ = 'Users'
uid = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(30), nullable=False)
mail = db.Column(db.String(90), nullable=False)
pw = db.Column(db.String(256), nullable=False)
if __name__ == "__main__":
app.run(debug=True)```
this is code
:v
can anyone help?
whats error?
also a: don't post your secret key b: that's an awful secret key, generate one using os.urandom or smth
@fickle fox
is it possible to create a variable name using javascript based on an user input?
no.
@proper hinge I get the meaning, but have never heard that expression. care to elaborate?
x is what they really want to do and y is how they want to do it, but y is not actually a good solution for x
So they should be asking how to do x, not how to do y.
i.e., the root of the problem
@proper hinge I have a problem. Can you help solve it?
I just the need the idea.. rest I can code
I'm not sure. What is the problem
So basically I have 5 setintervals. Now, I want to stop a particular interval and want to keep the rest running as normal. So, what should I do?
Use clearinterval to stop the one you need.
Why does the name need to be user-defined?
yea that's a pretty cool solution. But the problem I am facing is : suppose 100 users set their setintervals. Now, I wanted to assign them to variables which would be suggested by the users to keep it more comfortable.
Why? Cause you need to be able to stop a specific user's interval?
yea!
If that's the case, store the interval ideas in a dictionary
And use the user's ID or something else to identify it
Hello. I am having my Django project on github as private repository, but I posted some screen online about ideas for development and some guy askes sincere about checking my github code and giving me more specific advice. Is it safe to share my github code? I have all the files there, including settings.py and my sqlite3 database.
If that's the case, store the interval ideas in a dictionary
@proper hinge what do you mean by dictionary?
@maiden kraken does your settings.py contain Secret Keys and other private data?
yea objects are fine but still, is there not any more easy techniques?
I don't see how it could get any easier
it is safe to share code if it is just code....
Im afraid it does. What is the meaning of secret code anyway?
(unless you have bugs you can exploit lol)
Should I input new setting.py without secret code?
The proper way is to keep SECRET_KEY and database settings outside of your repo.
You should definitely never ever commit your database (unless it's for a test app).
@proper hinge So, you say that making objects will be better?
You can technically create variables with dynamic names, but this involves essentially modifying an object anyway, so it's a more hacky way of managing your own object. It's not really advantageous since presumably you'd need to dynamically retrieve those same variables too.
Can setinterval functions work while being inside an object?
Should I input new setting.py without secret code?
@maiden kraken you would have to change the secrets...
Once they are in git, you can easily see past commits.
so where am I storing the functions?
Just removing it won't scrub it.
By using the ID they return
setinterval returns an ID. If you pass that ID to clearinterval, it will stop it
oh man, I didn't even know that
@lethal orbit yeah I know I messed up. It was hard for me since I learn git as well with this project. Anyway I think since this is just a side project for portfolio I can share it
How do I get that ID ?
Like I said, it's what the function returns
@lethal orbit thanks for advice
Do you have the website running in production @maiden kraken?
no, I am still running it from local server, I use git as a private repo basically as a safe copy
Where do I store the ID and how do I interpret it?
Well, if it is not running in production, sharing it won't shouldn't hurt ๐
thanks a lot, you are not helping me the first time, I really appreciate your help ๐
Store the ID in an object
so a setinterval will have a specific ID Right and it wont change?
Extracted from the object?
It is returned by setinterval
I've noticed you have asked that a few times. Are you unfamiliar with how functions return things?
Yea
Haven't worked quite well with these things tbh. I've been focusing on deeper front end stuff (without deeper js)
@proper hinge What about I give the user the id to keep it with them? lol
Whenevr they want to force close the intrval, they can just enter the id
let id = window.setInterval(...)
window.clearInterval(id)
@maiden kraken the proper way to do things:
# settings.py
SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY") # and save a key in en environment variable called DJANGO_SECRET_KEY
# do the same thing for Database Settings if you use postgres/mysql which require a username/pw
And add a .gitignore file:
# Database
sqlite.db
# Editor settings
.vscode
.idea
``` etc.
Basically that, except you need to store each id in an object to associate it with a certain user
@lethal orbit Thank a lot, my laziness is just biting me in the ass, I wanted to push forward with the code as far as I could and ignored... ignoring ๐ It's a lesson for the future
All good. part of the learning process ๐
Each function returns something different, as functions are designed to perform different tasks. Some return nothing even. You'd need to read the documentation to know what each function returns.
My decisions also always bite me in the ass months down the line lol
yeah, might as well get use to it ๐
aight thanks friends! It really helped me1 ๐
You can also look for .gitignore files online: https://github.com/github/gitignore ... Python.gitignore is a good starting place.
let a = setInterval(function(){console.log('a')},2000); let poke = { "o1" : setInterval(function(){console.log('a')},2000) };
clearInterval(poke.o1);
why did it not work?
the interval kept on repeating
you mean the window?
https://github.com/chocotacove/chirp
This is my first complete project, first time writing readme.
Is the readme good, what changes can I do?
could someone help me figure out why flask bootstrap is not using grid even though i made the classes grid?
oh, so using the current documentation won't work :/
Yup
I did not kno that it used v3, ty!
Hi again, I am making a discussion board site. I have now login and logout functionality. How do I get username if the user is logged in and auto input it into a form so when the post is added it is added by this user?
This is my views.py but this doesnt work
def add_response(request): if request.user.is_authenticated: if request.method == 'POST': new_response_form = CreateResponseForm(data=request.POST) if new_response_form.is_valid(): new_topic = new_response_form.save(commit=False) new_topic.author = request.user.id new_topic.save() new_topic_form = CreateResponseForm() else: new_topic_form = CreateResponseForm()
are u using the default User model?
hmm yes, I also am extending default User with 1to1 relation but I think that is not changing much
right
in ur code, u have got the user id by doing request.user.id, you can get the username in a similar way, request.user.username
hmm, I think i don't really care if it is user id or name I think.. Problem is I get this:
NOT NULL constraint failed: homepage_forumresponse.author_id
and then
params
[None, '<p>test</p>', '2020-09-17 18:25:09.355271', 1]
first none is the author from what I assume
and it's None instead of name/id
yeah, from sql query I see that author is empty
Okay, managed to solve it myself thanks
Hey does anyone know if there's any danger of SQL injection in simply using request.POST.get(...) to access POST body data from a form with Django?
I use the data from request.POST.get(...) in the constructor of an object that will be stored in the database, but I'm pretty sure it utilizes the ORM so I should be safe, right?
I don't write any SQL commands, just call the object's save method.
@topaz widget im a beginner, but isn't csrf_token protecting you from this in any way?
@maiden kraken No, CSRF token protects against cross-site request forgeries, not SQL injection.
Very different method of attack.
@maiden kraken You should definitely read up on SQL injection, CSRF (cross-site request forgeries), and Cross-Site Scripting (XSS). They're probably the most common hacking methods / vulnerabilities for web applications and each require different practices to defend against.
anyone know an easy way to have a side nav in boostrap 3?
@topaz widget Thanks a lot for the tip, I will definitely check that out before finishing my project
oh nvm found a link
@hallow jacinth Why are you not using bootstrap 4? I think that's what version they're on now.
because flask-boostrap doesn't support it, and I am too lazy to go and download and use raw bootstrap 4
@maiden kraken Sure thing. The basic gist:
CSRF: Exploiting your authentication to make sensitive requests from outside your session.
XSS: Exploiting an insecure web application that allows raw user-generated HTML to inject JavaScript into the application.
SQL injection: Loading SQL (Structured Query Language) commands onto the database, which are not handled property to access or modify information the user shouldn't be able to.
Some of these attack methods can be used in tandem.
For instance, XSS can be used to pull credentials (cookies) from another user of the site, which then can be used in a CSRF attack to make privileged requests under the identity of the user whose identity has been stolen.
Since you're fairly advanced, I guess using something like tinyMCE and allowing storing html into your models isnt very safe?
Well, nothing I'm working on requires tinyMCE, but I have messed around with it a bit.
But yes, I would use something like that so users can't write their own HTML.
You can manually "white-list" certain HTML if you want to let users get more creative, but it's a pain in the ass to implement.
it's just scares me since I am using python as a hobby how much stuff you have to know ๐
It's good that you're scared. There are a lot of ways things can go wrong that won't even cross your mind as a non-expert.
https://github.com/chocotacove/chirp
This is my first complete project, first time writing readme.
Is the readme good, what changes can I do?
@coral raven
"Drop a star" lol, sounds like a youtube video.
Even the expert miss vulnerabilities, too.
I don't know if you remember the HEARTBLEED vulnerability, but that was a big deal not too many years ago.
I am reading about it, as you said, if you do something there is always a risk
It really depends on how secure your application needs to be.
@topaz widget and to answer your questions, django queries are escaped
@near forge lol thanks. I'm here for my own security concerns.
Anyway, if you're making bank software, that better be airtight.
Before you concern yourself about security, you should ask yourself what you are securing.
If you're making some rant blog, it probably doesn't have to have NSA-level security.
thanks for a nice discussion, I g2g
np, take it easy.
@topaz widget hopefully you have colleagues and tests before pushing bank software to production.
Yes, of course. But even professionals miss things. Kevin Mitnick has entered the chat
Better yet: Frank Abagnale has entered the chat
Though Abagnale was check fraud.
("Catch Me If You Can" was based on his exploits)
Anyhow as in any company, security should be on par with the services you provide.
There's really no point in making an air tight social app that no one uses.
But of course when money is involved. The best thing you can do is implement SOTA protocols for handling it.
That's just a waste of time imo.
It's an endless task.
SOTA? State of the art?
yes, usually there's is someone out there that's thought about security. As in django things are pretty secure if you just follow the guidelines.
My point is it's usually a better and easier to use already existing tools than implementing your own security measures.
You mean like not writing raw SQL commands, only using the | safe filter when you know you can trust the content, and using csrf_token in all your forms?
I guess, you better read the docs. I don't know them all by heart.
Oh yeah, right, there are a bunch of others on their "checklist" I wasn't thinking of (but use)
Anyone familiar with httpresponseredirect?
I'm redirecting a user to a google api link, they sign in, authorize access, confirm, etc, then it returns with the "code" necessary in the redirect URL so that I can next fetch a token.
However, it seems that my code might need to pause momentarily until the user finishes all of this stuff. Otherwise, code keeps running and I get errors b/c response not back yet from user's actions.
My question is http response redirect the best tool. or even if it isn't, should i be looking to something like celery to make a task scheduler?
Hey guys anyone know how I can run a function at a time specified by the user In flask
@clear fjord cron. Not in flask though, in Linux.
Actually, wait, maybe cron isn't so good if the user is specifying the time.
Yea
I was looking for a code solution
And since my client is not hosting on his laptop because its a small program just for him
if it restarts
it also needs to re add the tasks
I'm not sure how you would do that from within Flask.
Right now im just saving the entries in database
Maybe you could use time.sleep() and then just specify the time between when the user made the request and when it's supposed to happen.
I was thinking run the function from a url
and take an id in the url
and run the task depending on id and have another program run the url
or something
messaging queue maybe?
Although, I don't think time.sleep() could be done asynchronously, so maybe that's not such a good idea.
let me see if it can be used asynchronously
maybe some library or something i dont know
Well, you can write an asynchronous function.
I'm just saying I don't think time.sleep() is natively asynchronous like setTimeout in JavaScript is.
node flask hybrid ๐ณ
lol
i never used node
How tf are you using node with Flask?
im not lmao
It sounds to me like some asynchonous function might be best, but...
you might run into problems if a lot of users run asynchronous functions.
So this is only for him? And he is admin?
yea
What OS is he using?
Just use task scheduler then.
k let me try that
Are you on Windows?
@topaz widget task scheduler like celery. I'm wondering though are you able to break a function into 2 tasks. like
def main():
task 1 do something
httpresponseredirect
celery wait until http response is back from user completing action on a different url
task 2 do something else
return
@weak chasm No, Windows Task Scheduler.
This is admin-level stuff. Could just be done right on the system.
And it might be better for this guy to use Windows Task Scheduler if he's not a coder himself.
Although, I don't think
time.sleep()could be done asynchronously, so maybe that's not such a good idea.
@topaz widget it's not; you would useasyncio.sleepin that situation
you should ping omar on that message, too.
Anyone familiar with httpresponseredirect?
I'm redirecting a user to a google api link, they sign in, authorize access, confirm, etc, then it returns with the "code" necessary in the redirect URL so that I can next fetch a token.
However, it seems that my code might need to pause momentarily until the user finishes all of this stuff. Otherwise, code keeps running and I get errors b/c response not back yet from user's actions.My question is http response redirect the best tool. or even if it isn't, should i be looking to something like celery to make a task scheduler?
@weak chasm what backend
@vestal hound very new to webdev. Idk what you're talking about. lol
I'm using python django with heroku , but not not really using their built in middleware or whatever else they have.(Turned out I like flask more, but too late to go back)
@vestal hound very new to webdev. Idk what you're talking about. lol
I'm using python django with heroku , but not not really using their built in middleware or whatever else they have.(Turned out I like flask more, but too late to go back)
@weak chasm so Django is your backend
vanilla Django or DRF?
how do i check?
oh vanilla
so basically
you have a view where you need to do two things: get some data from somewhere else, and get some data from the user
and you only want to proceed after both of these things have been done
correct?
huh.
why do you want to use a redirect then
seems a bit complicated
async views should work just fine
actually, wait, let me think
I need the user to login to their google account and confirm authorization for my web app so I can get token access in future and play around with that stuff.
feels like
you're trying to solve multiple problems at once
maybe you can list out the steps in the intended experience from the user's perspective
- type my webapp url into browser
- my web app will redirect you to google api website so you can login and confirm access to my application
- user should be taken back to the my webapp.
- I will take the code embedded within the redirect url to fetch the token to have future access of the application
- list emails or list file in drive for the user
- do some magice on emails and files to create some end product for user
- user does some stuff
? i guess O_o
oh i added 5-7
ohhh so if the users not done:
the problem is that how does my web app know how fast or slow the user is when loggin into their account and checkboxing the stuff in google api .com website or w/e the url is. my code redirects sure but it keeps going and is thinking it already has the redirect url with the embedded code needed to fetch token. but it doesn't b/c user is slower than a computer executing lines of consecutive code.
ah, okay
because
you have redirected
so you don't know if the user is done.
is that what you mean?
so
httpresponseredirect(url) --> user goes through the motion of loggin in at google.com
code= request(url).url or something ==> user is not done yet with loggin in&authorizing
code. split("&") --> user is still not done
*here computer throws error variable called 'code' does not have more than 1 element in the list or ssomething like that *
correct
so there shouldn't be code running in your view after that...?
because you've already returned
well, then your redirect won't work, if I understand what you're saying correctly
it's not a function, it's a type of Response
do you know how HTTP status codes work?
I know of them. not sure how the codes affect the views.py
like 404 not found and 500 you messed up
yup
so basically
you know how your views
return responses?
HttpResponseRedirect is just another kind of response, but with a special status code that tells the browser that receives it "hey go here"
it's not a function thaty ou call
o_o
woah
my views return responses?
return render(request,"index.html")
i guess that's a response
should i be making a views.py helper function that just redirects
and I don't have to worry about the async responses
I'm going to try to break up function so I return httpresponseredirect
thanks
yes, render returns a HttpResponse
@weak chasm Are you trying to render templates to JSON or something? What are you trying to do?
If you're using Django, there are some native functions for doing simple redirects.
If that's all you're trying to do.
writing the oauthorization code to ask user to go to google api website(automated not manually) they login and confirm access then it comes back w/ redirect with "code" value within the redirect url. i take that to complete the token fetching process so in the future I dont have to ask the user again. and i'm able to read/write files in say gmail now
I didn't know/ still a bit uncertain how views handles httpresponses, (just know that they do and will be using this fact forward) and then send that to my page index.html. I saw some examples that were deprecated/only for flask that made a class inside models.py.
I don't think you can do that with gmail.
you can automate it. you just have to have the user login once at the beginning manually.
The user would at the very least have to change a setting in their gmail account.
I think that would require "allowing insecure apps" to access your gmail via something like SMTP.
idk, maybe there is an API, though. I guess there could be.
there is a google api for server side web applications. even some example code for flask(not django) interestingly enough, after searching for some examples, I found that the google's api authlib i think or something had some sample code for django in git repo. they deleted it. and aren't updating it only maintaining it. even more interesting, the old sample code was for using google plus. so i'm thinking the security fiasco w/ google plus couple years back made them ctrl+f google plus delete all.
change the setting=> yes. was thinking of even automating this one time sign with selenium. but that's too much work not enough reward.
https://developers.google.com/gmail/api/auth/web-server
that one seems more complicated than the one for drive
You can have a basic html web page and then have python scripts to make things happen on the page? Or how can I integrate python to html exactly
@plucky tapir I think you want to use JavaScript for what you're thinking about. Python is used on the "back-end".
Python is used on the server (back-end) to serve up HTML, CSS, and JavaScript (and media) files to the client or browser or front-end.
Sounds like you're just getting started on your web development journey.
That's why these forums exist, though.
Is there a big learning curve for JavaScript? Mainly have to function rather than look nice.
So assuming a basic webpage was built. That had made up user information stored in a database. Iโd use python to pull that data, do something to it (add 1.3 % increase for example) and use front end to display it?
that's pretty much right.
It's pretty easy to get started with JavaScript but there is a long path to becoming very good with it. Same with Python.
Here's a little more detailed run-down of what each component does in the "web stack":
Yeah just c++ for me and some concepts with python. Never implemented any of it to actually create something before though
HTML: Formats content on a web page. Used for semantic (meaning) and formatting purposes to mark content (called markup)
CSS: Styles HTML content. HTML tags are queried with CSS to apply styling to different HTML elements.
JavaScript: Manipulates the behavior of content on a web page. Can run full programming logic including loops, conditional statements, etc...
Python or Other Backend Language: Serves up content. Accesses database, crunches numbers before sending content to frontend. Processes requests sent from client (frontend)
JavaScript can sometimes serve as a backend then if youโre real into it?
What section of python would I want to look into more for this type of backend with python?
C++ isnโt really useful here it looks like
@plucky tapir it can serve as backend completely
@zealous siren with JavaScript?
@plucky tapir Some people swear by JavaScript (running on a Node.js runtime) for back-end, as it streamlines the development process only needing to use one language for both front and back-end (only JavaScript can run on the front-end).
I don't know if it's really comparable to C++, but C# is a popular language for the web back-end using Microsoft's .NET framework.
I'm not sure what you mean by "section" of Python, but there are some popular Python web development frameworks, notably Flask and Django.
also FastAPI
hello
I am making a google extension
is there a way to write and read to files in vanilla js
i only found stuff that works in node
i am noob
forgive
nope
when i tried exporting a file, it said it was an invalid token
export is invalid token
Javascript is offtopic
wdym
Well, not necessarily. It's fine if it's related to something you're doing in Python. But, for example, talking about using nodejs to run a webapp or use js to make a chrome extension are not really on topic here
This may not be the right channel, it's a Git questions. Please...
Hi, I've never gotten this message when i've made a commit in the pawst.
-
Why would this occur?
-
Should I suppress it? or what should I do?
[master 189a579] Content is showing over the foreground image, but footer is still risng above overflowing, and content is overlapping strangely.
Committer: Brian Boros Bpower@tests-MBP.attlocal.net
Your name and email address were configured automatically based
on your username and hostname. Please check that they are accurate.
You can suppress this message by setting them explicitly:git config --global user.name "Your Name"
git config --global user.email you@example.com
After doing this, you may fix the identity used for this commit with:
git commit --amend --reset-author
1 file changed, 1 insertion(+), 1 deletion(-)
No it's not the right channel. git is not related to web development
please ask in #tools-and-devops
Thanks I'm new to the pyton group and will be more active soon, but thanks a ton.
learn the ettique I read the rules...
@topaz widget Iโll jump into flask framework to start learning how to get the database data and do something with it. From there html can use it to output on a page?
more or less, yes @plucky tapir
Just don't set your sights too high this early on. Learning this stuff takes time.
Django Rest Framework: How many requests is too many?
I have a page on my frontend which shows 10 Posts. Each of them is associated with multiple Tags and Images. And all this data needs to be fetched from multiple different views. So when I load up this page in my browser about 20 requests are made to my backend. Is this normal/okay?
If it isn't, then what can I do to minimize them?
I am using Vuejs as my frontend if that matters.
Please @ me when you reply
@topaz widget Okay thanks. I've been using nano for python. Should I be looking into IDE's for this? I'm looking It looks like VS code and pycharm is the most popular recommended. I'll be looking at sql + python tutorials for now
@plucky tapir vscode is pretty popular. That or Pycharm would be good options.
@topaz widget my bad for all of the questions. One last thing I was wondering, a user on a website (made by html) inputs data. Would it need python to get pushed to the database?
@plucky tapir You've got a lot to learn. First of all, all websites with user interfaces use HTML on the front-end. HTML gives different elements on a webpage their special meaning. One such element that has special meaning is called a <form> element. This form element is how users submit data from a web page to the back-end for something like Flask or Django to enter into the database. In answer to the other question, Python, or more specifically a framework like Flask or Django, would have some protocols for entering that data into the database. So, essentially you're correct, but there is a lot more to it. Anyway, I'm happy to answer questions, but a new episode of "The Boys" just dropped, so I'm going to log off Discord for now. Keep asking questions. That's the right approach.
@versed python I try and batch as much as possible.
@versed python 20 requests for a page (with all the content) is not too much. I'm not sure this is something to be concerned about unless your application feels laggy.
I think you'll know when you're asking too much from your application.
20 requests for a page isn't bad, unless that number of requests can scale
There may be ways to combine the page into fewer requests (that's beyond me), which may take out some of the overhead associated with each 'handshake', but I don't think you're anywhere close to having to worry about that.
@topaz widget @tepid lark thanks for your insights. However you mentioned "batching". What is that? Can you explain it a bit or provide some links?
Django Rest Framework: How many requests is too many?
I have a page on my frontend which shows 10
Posts. Each of them is associated with multipleTags andImages. And all this data needs to be fetched from multiple different views. So when I load up this page in my browser about 20 requests are made to my backend. Is this normal/okay?If it isn't, then what can I do to minimize them?
I am using Vuejs as my frontend if that matters.
@versed python are you making one request per instance?
why canโt you fetch everything you need together?
Good point, as it's an API
20 requests seens to imply at least 20 queries.
It should all just come as one JSON string.
and yeah, if that can scale you will probably have a problem down the road
How so? @vestal hound
How so? @vestal hound
@topaz widget I mean, that number of queries
like N+1
not what you said about JSON
Oh, okay. Yeah, I mean, 20 isn't terrible for an entire page including media, though, is it? @vestal hound
Granted, I don't use DRF, but I see the requests using Django in the standard manner, and it can be quite a few if there are a lot of pictures.
well
I took it as 20 on initial load for just data (like models)
which would be a huge lot
if itโs 20 over time due to scrolling or something + including one per image + fetching other stuff separately
then I would say itโs fine
So you're talking about AJAX calls?
yup, basically
I mean, I guess it's all AJAX with an SPA
I don't really know how to do that
why canโt you fetch everything you need together?
@vestal hound this I mean
I am limited by my serializers and since I am using viewsets a lot, that also means I have to send requests to different paths of drf
Is there a better way?
I am limited by my serializers and since I am using viewsets a lot, that also means I have to send requests to different paths of drf
@versed python oh
well
that's why I guess
you know how to write nested serializers?
that's probably what you want
can I do something about it?
nested serializers?
I don't know them
you have this data model
I guess ill have to look at em
Does django graphene make this stuff easier or does it remain the same?
wait, this doesn't make any sense
I just woke up
let me get some water and I will fix the example
Yeah sure, take your time
Or you can just tell me what link to look at, I will try to learn from there
anyone how to create a azure server replica in your linux machine ?
class Song:
artist = models.ForeignKey(Artist, related_name='songs', delete=models.CASCADE)
name = models.TextField()
lyrics = models.TextField()
class Artist:
name = models.TextField()
date_of_birth = models.DateField()
Does django graphene make this stuff easier or does it remain the same?
@versed python I found it to be horribly hard to read and extend, and recommendariadneinstead.
so say you have this, right
each song has an artist, and each artist has multiple songs
But GraphQL as a whole makes it very easy to fetch all the data in one query.
@versed python I found it to be horribly hard to read and extend, and recommend
ariadneinstead.
@lethal orbit I looked at it the other day on your recommendation and could only find photos of some greek goddess(?)
so you'd have an ArtistSerializer and a SongSerializer
Google "ariadne graphql"
Oh
Ok, so tell me should I go with this aridne or nested serializers approach
by default, related models are serialized with PrimaryKeyRelatedSerializer
Ok, so tell me should I go with this aridne or nested serializers approach
@versed python up to you
GraphQL is more foreign but (I would say) more powerful
Which one is better?
But GraphQL as a whole makes it very easy to fetch all the data in one query.
@lethal orbit This does make it seem "better"
REST as a style
is honestly quite foreign
to most people
so one tends to end up writing RPC code
which is fine, but not REST
so I guess what you got was something like
GraphQL is more modern and powerful. REST has been around forever, and many jobs still expect it. I wouldn't use it in a new project, tbh.
{'name': 'some_artist', 'date_of_birth': '1963-03-05', 'songs': [1, 8, 34, 494, 2395]} from your serialized Artist
But REST isn't bad, of course.
GraphQL is more modern and powerful. REST has been around forever, and many jobs still expect it. I wouldn't use it in a new project, tbh.
@lethal orbit But I have seen you using them in projects
true REST is really hard to write iMO
{'name': 'some_artist', 'date_of_birth': '1963-03-05', 'songs': [1, 8, 34, 494, 2395]}from your serializedArtist
@vestal hound Yeah go on
I have used both, yes ๐
you probably loop through those song IDs
DRF was an older project haha
class Song:
artist = models.ForeignKey(Artist, related_name='songs', delete=models.CASCADE)
name = models.TextField()
lyrics = models.TextField()
class Artist:
name = models.TextField()
date_of_birth = models.DateField()
@vestal hound (For reference)
and get songs one by one and put them into the SongSerializer
but you can also do this
class ArtistSerializer(serializers.ModelSerializer):
songs = ...a custom serializer for a queryset of songs...
...your other fields...
class Meta:
model = Artist
fields = ['songs', 'name', 'date_of_birth']
so that when you serialize your Artist, it becomes a nested JSON
like:
{
'name': 'some_artist',
'date_of_birth': '1963-03-05',
'songs': [
{
'id': 1,
'name': 'some_song'
...
]}
yes
Great
HyperLinkedModelSerializer basically returns a URL saying "go here for more details about this resource"
that doesn't look too difficult to implement
well.
๐
I mean
it's a good part of the learning process
I had hell with these things a couple of months back
Well I am having hell now ๐
ANd javascript is shit but I have to write it anyway
different
and like
if you try to write code that does not conform to the REST paradigm
you will start fighting the framework
which is painful
There's a paradigm??
Representational state transfer (REST) is a software architectural style that defines a set of constraints to be used for creating Web services. Web services that conform to the REST architectural style, called RESTful Web services, provide interoperability between computer sy...
God
technically REST is a way to write APIs
why is everything so difficult lol
you don't have to follow it
you can just write an RPC API
so basically like
think of your application as a Python module
and each view as a function in it.
that is fine.
REST is a different way of thinking about APIs
in terms of resources
and operations on them
and it's really a bit technical and after a while you'll start thinking "why must hypermedia be the engine of application state" etc. etc.
Lol, I am probably not too good to get to that stage yet
Anyways thanks @vestal hound , I will look into the resources you sent. Thanks
yw
GraphQL is more modern and powerful. REST has been around forever, and many jobs still expect it. I wouldn't use it in a new project, tbh.
@lethal orbit I think one drawback of using GraphQL with Relational Database is that you can't optimize the database queries anymore, unless there is a way that I'm unaware of
Optimize how?
okay let's say in a given serializer, I know that I'll be providing so and so foreign key data, so I'll be using joins to return those values from the View.
but in GraphQL, the user can query whatever the fields and data they like
If you have data with joins (foreign keys, many to many), you can still use prefetch or select related in your query, and add that field as a resolver...
If you have data with joins (foreign keys, many to many), you can still use
prefetchorselectrelated in your query, and add that field as a resolver...
@lethal orbit which is equally necessary in all cases, anyway
it's not a problem particular to GraphQL
so I'll be writing cases in my view that'll check whether the given field is present in query sent by the client and create joins in those scenarios only?
so I'll be writing cases in my view that'll check whether the given field is present in query sent by the client and create joins in those scenarios only?
@marble carbon a library should handle that
and provide an appropriate abstraction
ohhh they do? that'd be nice
I recently made a Web API that implements both GraphQL and REST endpoints, if you'd like an example. Implemented via FastAPI: https://docs.coursecake.tisuela.com/REST-API
By serving course ๐ data that is more โedibleโ ๐ฐ for developers, we hope CourseCake offers a smooth approach to build useful tools for students.
im trying to install twisted and i keep getting erros and im wondering what i should do
im running python 3.8
feel free to @ me
If you don't post the errors we can't hardly help you
@gentle lark yup. Post error log. I just installed it in a clean venv and it worked fine.
(I actually did need to start a project with it lol)
Lol
@lethal orbit i think its because i might have python 32 bit by accident
i think i can upgrade to 64 bit and it should work
Try it and let us know I guess
@lethal orbit installed 64 bit but error persists
so im gonna try to reinstall the c++ build tool from vs to see if that fixes it or not
Hello, this is useful in django:
ModelName.objects.last()
but I would like to access date_of_publication field, this returns str method
meaning i need to go deeper into model, return field that I want, how do I do that?
well I am an idiot... You do just:
ModelName.objects.last().date_of_publication
but you have to make sure that there is actually an object to return because you may get NoneType and wonder why it isnt working ๐
class Post(models.Model):
author = models.ForeignKey(
'accounts.CustomUser', on_delete=models.CASCADE, related_name='post_author'
)
class PostImage(models.Model):
image = models.ImageField(
_("An image to go with your post"), upload_to=user_directory_path
)
post = models.ForeignKey(
"posts.Post", on_delete=models.CASCADE,
verbose_name=_("The post that the image is associated with")
)
i know I can add multiple PostImage to Post using
post = Post.objects.get(id=1)
images = PostImage.objects.all()[:10]
for image in images:
post.postimage_set.add(image)
However, I was wondering if there was a better way of doing this without making a for loop? I was thinking about post.postimage_set.bulk_update but that did not work.
that is not related and I hope you don't mind, why do you have "posts.Post" instead of "Post"?
that is not related and I hope you don't mind, why do you have "posts.Post" instead of "Post"?
@maiden kraken That is another method of describing an FK. This way, as you can see inPost.author, i don't have to import the CustomUser model. Django can figure out what model you are referncing to by itself. this is a better way imo.
you can reference another model by '<app-name>.<model-name>' or just '<model-name>' if your models are uniquely named (which they should be).
okay thanks a lot for explanation
@worn rapids github link pls?
hi EveryBody ๐,
someone for helps?
i create data in my test environnement.
i use it to confirme the file is delete when i use the value of delete !
it work ! but not on the good side because my date is delete for real.
so i search on the web ! but i donโt found how can i get a copy of the file in my test environnement ( pytest / pyramid ) in init.py TEST_Zip2 = join(dirname(file), โUnZipโ, โtest2.zipโ)
#layout.html
<a class="dropdown-item" href="{% url 'login' %}">login</a>
#urls.py
urlpatterns = [
path('register/',views.register,name = "register"),
path('login/',views.loginUser,name = "login"),
path('logout/',views.logoutUser,name = "logout"),
]
when i runserver NoReverseMatch at /
Reverse for 'login' not found. 'login' is not a valid view function or pattern name.
whats wrong here ๐ฆ
in urls.py do you have app_name = 'something'? If so you need to pass to template href="{% url 'something:login' %}
'appname' is not a registered namespace
i registered app name in urls.py but im missing something
maybe you didnt add it to the INSTALLED_APP?
@versed python wait, hold up; how do those PostImage instances exist without a Post, originally?
maybe you didnt add it to the INSTALLED_APP?
@zinc hill added
i think i have problem with main app in urls.py
@versed python wait, hold up; how do those
PostImageinstances exist without aPost, originally?
@vestal hound I haven't but any db level constraints in place but I don't give my users ability to add PostImage without a Post first
@vestal hound I haven't but any db level constraints in place but I don't give my users ability to add PostImage without a Post first
@versed python huh. I would've thoughtForeignKeyfields were non-nullable by default
why didn't bulk_update work for you?
@tacit comet what about the
Applicationname url?
did you point it to the your new app?
for ex: project call "food"
and you made anotehr app called "account"
did you change the food.urls to point to "account.urls"?
why didn't
bulk_updatework for you?
@vestal hound idk how it works. Will it work for my use case? then I will read up the docs a bit.
hey guys, i'm building a web app and i'd like to check if the emails provided actually exists, i use this library
https://pypi.org/project/py3-validate-email/
but the parameter
check_mx: check the mx-records and check whether the email actually exists
can anyone tell me how to resolve that or has another library to propose me ?
@tacit comet what about the
Applicationname url?
did you point it to the your new app?
for ex: project call "food"
and you made anotehr app called "account"
did you change the food.urls to point to "account.urls"?
@zinc hill i handle it thank you
hey guys, i'm building a web app and i'd like to check if the emails provided actually exists, i use this library
https://pypi.org/project/py3-validate-email/
but the parametercheck_mx: check the mx-records and check whether the email actually existscan anyone tell me how to resolve that or has another library to propose me ?
@strange briar what do you want to resolve?Just usecheck_mx=Truein thevalidate_emailfunction
yes Ignis that's what i did yet it doesn't work, keeps running
nvm it works it's just that it's slow
anyways to implement a faster verification ? or should i just use regex
yes way too slow
yea but i can't let a user wait 4-5 secs on registration form
so this must be done via front-end in your opinion ?
<a class="dropdown-item" href="{% url 'student:register'%}"> register </a>
{% endif %}```
there is any easy way about this ? ๐
can't think of any
its fine to have logic in the navbar section tho
but u should try to implement logic in view mostly
in ur case, u can't really do that inside the view, hence in the template
anyways to implement a faster verification ? or should i just use regex
@strange briar Do you need to verify the email exists? Then this is your best bet. Otherwise use withcheck_mx=Falseit will be pretty okat
Oh wait, i just checked. Turns out I don't use this library at all @strange briar I use validate-email. pip install validate-email
yea i checked your implementation too and validate-email is not up to date, it doesn't use py3dns
so the alternative is to use this
pretty much the same as the previous one
they all do the same job but the speed remains the same
it does implement pydns
it display an error if you use the check_mx
you didn't implemented it so you didn't see it but i did
it's default to False
yes I do remember that
thought it was just an issue with my pc
well good to know
ill change my dependencies too accordingly, thanks
oh well, you can write a custom endpoint that accepts an email and return its validity only 8n json response, and then you can call it from ajax on your page
i see thank you thunder ๐
i've got another question i'm implementing some basic testings on django test for my user table
and i get errors while i shouldn't
from django.test import TestCase
from .models import CustomUser
# Create your tests here.
class CustomUserTestCase(TestCase):
""" Base user table testing """
def setUp(self):
# Create valid users
user1 = CustomUser.objects.create(first_name="John", last_name="Doe", email="test1@gmail.com")
user2 = CustomUser.objects.create(first_name="Jane", last_name="Doe", email="test2@Outlook.com")
user3 = CustomUser.objects.create(first_name="Brian", last_name="Yu", email="test3@yahoo.fr")
# Create invalid users
user4 = CustomUser.objects.create(first_name="", last_name="Doe", email="test4@live.fr")
user5 = CustomUser.objects.create(first_name="Jane", last_name="", email="test5@Outlook.fr")
user6 = CustomUser.objects.create(first_name="John", last_name="Doe", email="")
user7 = CustomUser.objects.create(first_name="Jane", last_name="Doe", email="test@.com")
user7 = CustomUser.objects.create(first_name="John", last_name="Doe", email="test@O.")
def test_valid_CustomUsers(self):
self.assertTrue(user1.is_valid_CustomUser())
self.assertTrue(user2.is_valid_CustomUser())
self.assertTrue(user3.is_valid_CustomUser())
def test_invalid_customUsers(self):
self.assertFalse(user4.is_valid_CustomUser())
self.assertFalse(user5.is_valid_CustomUser())
self.assertFalse(user6.is_valid_CustomUser())
self.assertFalse(user7.is_valid_CustomUser())
and here are the logs
System check identified no issues (0 silenced).
EE
======================================================================
ERROR: test_invalid_customUsers (users.tests.CustomUserTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/leon/pers/Boutique-Leon/backend/users/tests.py", line 34, in test_invalid_customUsers
self.assertFalse(user4.is_valid_CustomUser())
NameError: name 'user4' is not defined
======================================================================
ERROR: test_valid_CustomUsers (users.tests.CustomUserTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/leon/pers/Boutique-Leon/backend/users/tests.py", line 27, in test_valid_CustomUsers
self.assertTrue(user1.is_valid_CustomUser())
NameError: name 'user1' is not defined
----------------------------------------------------------------------
Ran 2 tests in 0.010s
FAILED (errors=2)
Destroying test database for alias 'default'...
oh ok so the syntax should be like that
self.user1.assertTrue(user1.is_valid_CustomUser())
``` ?
every where you reference something from another class method, you must write self
oh ok so the syntax should be like that
self.user1.assertTrue(user1.is_valid_CustomUser()) ``` ?
@strange briar self.assertTrue(self.user1.is_valid_CustomUser())
still 2 errors
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
EE
======================================================================
ERROR: test_invalid_customUsers (users.tests.CustomUserTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/leon/pers/Boutique-Leon/backend/users/tests.py", line 34, in test_invalid_customUsers
self.user4.assertTrue(self.user4.is_valid_CustomUser())
AttributeError: 'CustomUserTestCase' object has no attribute 'user4'
======================================================================
ERROR: test_valid_CustomUsers (users.tests.CustomUserTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/leon/pers/Boutique-Leon/backend/users/tests.py", line 27, in test_valid_CustomUsers
self.user1.assertTrue(self.user1.is_valid_CustomUser())
AttributeError: 'CustomUserTestCase' object has no attribute 'user1'
----------------------------------------------------------------------
Ran 2 tests in 0.016s
FAILED (errors=2)
looks like the same
see edit above @strange briar
You might also have to use self.user1 = CustomUser.objects
ok great it works ๐
yes i did implemented that too
class CustomUserTestCase(TestCase):
""" Base user table testing """
def setUp(self):
# Create valid users
self.user1 = CustomUser.objects.create(first_name="John", last_name="Doe", email="test1@gmail.com")
self.user2 = CustomUser.objects.create(first_name="Jane", last_name="Doe", email="test2@Outlook.com")
self.user3 = CustomUser.objects.create(first_name="Brian", last_name="Yu", email="test3@yahoo.fr")
# Create invalid users
self.user4 = CustomUser.objects.create(first_name="", last_name="Doe", email="test4@live.fr")
self.user5 = CustomUser.objects.create(first_name="Jane", last_name="", email="test5@Outlook.fr")
self.user6 = CustomUser.objects.create(first_name="John", last_name="Doe", email="")
self.user7 = CustomUser.objects.create(first_name="Jane", last_name="Doe", email="test@.com")
self.user8 = CustomUser.objects.create(first_name="John", last_name="Doe", email="test@O.")
def test_valid_CustomUsers(self):
self.assertTrue(self.user1.is_valid_CustomUser())
self.assertTrue(self.user2.is_valid_CustomUser())
self.assertTrue(self.user3.is_valid_CustomUser())
def test_invalid_customUsers(self):
self.assertFalse(self.user4.is_valid_CustomUser())
self.assertFalse(self.user5.is_valid_CustomUser())
self.assertFalse(self.user6.is_valid_CustomUser())
self.assertFalse(self.user7.is_valid_CustomUser())
self.assertFalse(self.user8.is_valid_CustomUser())
looks like that now
btw this is not django stuff, this is python basics
actually
that's why it's not correctly implemented
you might have to brush up on basics a bit
i know about asserts
the way i implemented it following you is that i create an object
i keep this object and then i reference it directly
what i want to do is create this user
and then directly reference it on test_valid_customers via the db
i have to use something like this
def test_departures_count(self):
a = Airport.objects.get(code="AAA")
self.assertEqual(a.departures.count(), 3)
not repeat self
within methods that's fine. But you're referencing your across different methods
I m trying to build a chatbox /messaging app
But Django channels documentation ask for Docker installation for redis
Is it necessary?
I dont want to deploy the project ,just learning
Replied ^ on the Django server lol
Srry๐
I have one problem that is failing to be googled out. I have a django website and I'm working on its SEO, so atm I'm doing everything to make the website faster, and my last step is implementing CDN. Cloudflare is strongly recommended but I can't accept it for privacy reasons, as it is a man in the middle, having all user data flow in plain text on their servers. I don't think they really do anything bad with the data, but using it would require GDPR box appearing and user accepting it, which I don't want to force him to do. Is it possible to use some CDN type solution to serve static files only? So basically I only care about the speed-up without any other things like ddos protection while protecting user privacy fully.
I see a lot of people finding this issue with cdns on reddit, but there are no possible solutions suggested, are there really no alternatives?
You can do that fairly easily....
You're using Django templates?
I don't, but I think you basically have to set the statics settings to point to something like https://cdn.yourdomain.tld and point that to the CDN.
Really, that's it? :D
So I wouldn't even need to modify references to static files from within templates?
Thanks then, I'll read up on it. You use django without templates?
What are you using django for then?
Drf?
Haven't done those things yet
it was a joke
@lethal orbit I looked at it the other day on your recommendation and could only find photos of some greek goddess(?)
this
Thought that was the case
Ok, time to watch the Vue.js announcement,...
I bet it's Vue 3
quick question on django
i want to somehow make people unable to register usernames with similiar case sensitivity
e.g. people cant register as Jake if there already exists JAke
e.g. people cant register as Jake if there already exists JAke
@bright spindle validator on the username field
is that the best way
combined with check constraint at the database level
would it be the most ideal way
i still do want to keep the case sensitive username
but i dont want other users to have it
e.g. registering Jake allows noone to use JAke and other similiar names
however logging in allows Jake to type in JAke, and it will always be displayed as Jake
With validator, as gm wrote, you can write whatever python function
however logging in allows Jake to type in JAke, and it will always be displayed as Jake
@bright spindle that's a presentation layer concern
is there any documentation to lead me the way
not a check constraint, a unique constraint
@vestal hound this is a bit complex though
so you should probably go wit hthe validator
it's not perfect
but it's a lot easier.
in general you want to enforce this kind of restriction as deep as possible
arent unique constraints very strict
and you can't go deeper than the database
i know postgresql
arent unique constraints very strict
@bright spindle yes, a case-insensitive unique constraint onusername
Google django custom form validation
also is it more ideal to store a column with the case sensitive username
and let the web handle it
or have two columns
one case sensitive and one case insensitive
wait, go back
so how do you want them to log in?
should logging in be case-insensitive?
case sensitive
but the username should never be used no matter the case sensitiveness
huh
an username e.g. Jake
so which is it
I'm not talking about
tat
that
I mean
solely when logging in
case insensitive
then
why don't you just store
the lowercase version
always
and have a unique constraint on that
cause i like challenges
@marble carbon github to coursecake: https://github.com/nananananate/CourseCake
it was a joke
@vestal hound It actually wasn't. really happened to me lol.
ty
Question, does somebody know why it's not heading to index.html? Or is this even the right way?.. I will add a second image what shows maybe a bigger or different problem, but I am not sure. Hopefully some of you know. Thanks in advance
This is the result.
UPDATE: have enabled debug mode, and showed that I needed to install eventlet, have done that and now it's showing this.
Thanks for that 1. But I am having still the same problem. Do you maybe know what I am encountering?
@wanton tulip this is the simplest error. Did you fix it?
Well, I have put my index.html in a folder, now the 'jinja2..' error is over.
Need help?
Let me look for it, I am feeling embarrassed. Thanks for wanting to help.
Omg.. smh.. I checked the sourcecode 'templating.py'.. They even commented there, with an explanation.. Thanks atleast, I am embarrassed.
Was just reading over it in the docs..
Good๐
I have changed my domain from example.xyz to example.com finally after buying it from the owner.
Is there any way with cloudfare to redirect the old domain domain to the new one? I know of page rules but I want to preserve sub domains such as:
img.example.xyz/t.png
img.example.com/t.png
i get this with flask socketio ERR_SSL_PROTOCOL_ERROR
I dont have flask ssl cert but i have one setup on heroku
does anyone knows how to change the data from DRF serializer before send to the user?
"data": { "added_companies": [ { "code": "252151241", "company_data": { "id": 1, "status": "fake",
I want to retieve the list inside the added_companies and get something like this:
"data":{{code:2525.....},{code:2112....
After a month of learning Django, i actually start building projects of mine but recently i get confused, coz everyone's talking about React and telling me to use it, so do I really need to use it while I'm working with Django/jQuery ?
After a month of learning Django, i actually start building projects of mine but recently i get confused, coz everyone's talking about React and telling me to use it, so do I really need to use it while I'm working with Django/jQuery ?
@tiny dirge you don't have to use React
plain jQuery will be fine
(depending on what you want to do)
does anyone knows how to change the data from DRF serializer before send to the user?
"data": { "added_companies": [ { "code": "252151241", "company_data": { "id": 1, "status": "fake",I want to retieve the list inside the added_companies and get something like this:
"data":{{code:2525.....},{code:2112....
@frank nebula overrideto_representationin your serializer
Does anyone else struggle writing markup with lots of anchor tags, span elements, etc... while also maintaining a clear communication style?
I find the process of tagging everything takes me out of the "writer's head" mode.
I have been using ruby on rails and there was a gem delayed jobs for queuing long running tasks .. is there any similar thing in flask_restful for doing that?
I'm creating a test application using Flask on Python3.8.3, and it correctly receives my post request data, and my post request data is correctly being sent, but request.form is always empty, can someone explain why? (I'll link my code below.)
CODE: ```py
def WebMain(q):
from flask import Flask, request, make_response
web = Flask(name)
def GetFile(file):
try:
with open(file,"rb") as f:
data = f.read()
f.close()
return make_response(data)
except FileNotFoundError: return make_response("")
@web.route("/")
@web.route("/index.html")
def index(): return GetFile("index.html")
@web.route("/favicon.ico")
def favicon():
response = GetFile("favicon.ico")
response.mimetype = "image/x-icon"
return response
@web.route("/background.png")
def background():
response = GetFile("background.png")
response.mimetype = "image/png"
return response
@web.route("/verify.html", methods=["GET","POST"])
def verify():
if request.method=="POST":
print(request.form)
return "Yes"
else: return GetFile("verify.html")
print("Website has loaded!")
web.run()```
(Also the reason it's wrapped in a function is because I'm using multiprocessing.Process to run it and I'm importing it inside another script)
Console Output: ImmutableMultiDict([]) 127.0.0.1 - - [19/Sep/2020 12:53:04] "POST /verify.html HTTP/1.1" 200 -
Client command: py requests.post("http://127.0.0.1:5000/verify.html",json=[0,1,2,3])
(I'm only using requests.post because it's easier to test that way, in reality it's being sent by a browser)
hi
Hello
To whoever asked that unrelated question earlier, here's how I'd do it: py def MassDelete(s, c): if len(c): return MassDelete(s.replace(c.pop(), ""), c) else: return s
>>> MassDelete("ABCDEFGHIJ",["A","C","D","J"])
'BEFGHI'```
@fringe osprey str.translate is much more efficient
only needs 1 loop instead of n loops
where n== number of chars
I'd just do return "".join(_ for _ in s if _ not in c) or similar.
If c is a set instead of a list, even better.
I am not sure if this fits under this category its websites and database stuff but I have a wordpress website and I just wanted to know if their is a way to modify documents in mongoDB from my wordpress website through like html code or a button or something?
Wordpress is bound to mysql
Hey all I have a Flask app that uses Redis for task queuing and React in the front end. I am running all in a development environment on my macbook. I really want to deploy this to a VPS on like DigitalOcean/Linode. What is the simplest/most efficient way to deploy it?
There may be plugins for mongo with WP? I wouldn't know though, I haven't used that in years.
@cold socket docker-compose
Yeah docker is the way to go
no I check their are none unfortunately, I just prefer mongoDB as it is non SQL but...
Then you can write your own.... or use something in python lol
So I am hosting all my code on GitHub. When I need to push out an update does Docker integrate with Git some how?
@fringe osprey to get JSON data from the request, you'd use request.json
So I am hosting all my code on GitHub. When I need to push out an update does Docker integrate with Git some how?
You can use github actions to automatically build your containers, and deploy on push.
So I don't have to build the docker image locally? I can just build it based off my repo?
I use gitlab-runner with Gitlab.... it's defined in a yaml file. Github actions will be a bit different, but similar. https://gitlab.com/patryk.tech/patryk.tech/-/blob/master/.gitlab-ci.yml
No, but you do need somewhere to store it
You don't have to build it locally, but I do like a consistent flow, so I use docker for dev and for deployment.
github action to push to DO container registry and pull from there
No, but you do need somewhere to store it
Not necessarily. You can just build it on the VPS and bring it up, no need to push it anywhere.
Interesting, so when you start developing something in dev do you start with a container and develop in there?
yeah but that's harder to integrate with your CI
Yeah, I do.
yeah but that's harder to integrate with your CI
What? How?
Literally the same except minus the push lol
Ok good to know. I'll need to research some tutorials on containerizing Flask w/ Redis.
Thank you guys for the help!
#tools-and-devops is a good place to talk about docker and CI/CD ๐
I hadn't considered doing actions on your VPS as part of that
code goes in, artifact comes out
I am trying to run a flask application on Windows. I keep getting the error
Error: Could not locate a Flask application. You did not provide the "FLASK_APP" environment variable, and a "wsgi.py" or "app.py" module was not found in the current directory.
I have tried both set FLASK_APP=main.py and $env:FLASK_APP=.\main.py, but it just refuses to run. Can anyone help
check if the file is actually in your cwd
I am using virtualenv as of now. Does that make a difference?
no
check if the file is actually in your cwd
@warped timber yes, it is
@merry geode Nah its different. Install it using pip install python-dotenv and then create a .env file in the root
It'll make managing your environment variables much easier
how are you starting flask
@merry geode did you check if the variable is actually set?
@fringe osprey to get JSON data from the request, you'd use
request.json
@outer apex Thanks
like, in the first line of your script, import os; print(os.environ['FLASK_APP'])
@vestal hound doesn't seem to have been set
I get a KeyError on running that command
I don't really remember how to set environment vars on Windows
but, yeah, that's why you have a problem
windows is dumb
@lethal orbit From a development perspective, totally agree
Using \ is usually a bad idea.
But then, Flask is also dumb
lol, yeah. I have struggled a lot with that same error even on Linux.
@merry geode if main.py is in the root of the directory, you can ignore the .py extension
Nope, forward slash also doesn't make a difference
on Linux, it's export FLASK_APP=main
I'm telling you creating that .env file in the root will help you with your headaches
I can't remember what the export equivalent is for Windows
@merry geode https://pypi.org/project/python-dotenv/
The windows equivalent is
set
@merry geode probably syntax is wrong
Are you on Windows 10 btw?
@merry geode probably syntax is wrong
@vestal hound not getting any errors on running that command. It runs fine.
Also, I found it on a Flask tutorial itself
@cold socket Yes, Windows 10.
So I have .env file and I have put FLASK_APP=main.py in it. Now how to I use it
@vestal hound not getting any errors on running that command. It runs fine.
Also, I found it on a Flask tutorial itself
@merry geode in the sense that it's not setting the right thing
OK, got it. It ran, thank god. I needed to write python -m flask run instead of just flask run.
Thanks!
@merry geode I usually put these two lines in there FLASK_APP=app.py FLASK_ENV=development
And flask run always works
BTW, I was trying to use FastAPI at first. But some library called orjson just refused to get installed.
First it threw some error which got resolved by switching to Python 64-bit. Then it threw another error which should have gotten resolved by installing rustup, but got resolved only after selecting the nightly build of cargo or whatever. But then it threw a new error, at which point I just got frustrated and switched to Flask
Also I believe with Windows when you use "set" that only stores the environment variable temporarily. So if you start a new session you have to set it again.
And flask run always works
@cold socket I think there's some issue with my installation where flask run tries to run it with 32-bit Python and hence fails, but when I put python -m flask run, it finds the right interpreter
@merry geode That's unfortunate. I was actually looking to make the transition to FastAPI but ill wait till it matures a bit more.
Oh, no. Actually, after putting the .env file, even flask run is working. That's great. Thanks @cold socket
@merry geode That's interesting. Yeah I stopped using Windows completely since I switched to my mac. But glad to hear its working.
Actually, I had run FastAPI in the past myself. But at that time (actually, just 4-5 months ago) I was very new to web dev and Django just felt easier to get started with. I was not familiar enough to set up the entire project the way FastAPI and Flask require.
Now that I understand things a lot better, I thought I'll try it out, but for some reason now I'm not able to run FastAPI. Don't know what changed in that time.
I think starlette?
@warped timber hadn't heard of it. might give it a try
https://shortme.herokuapp.com/
i need suggestions
@barren stratus one thing to do is verify if the URL is legit before shortening it
Right so, what's your current set up right now?
Cool, have you set up Gunicorn/uWSGI yet?
It is, yes, though you'll have to set up those two things and configure Apache first
So basically, you know how like, Flask comes with this development server that basically allows you to check out what you're currently working on locally?
Basically you'd want to configure Apache so that domain.com/foo routes into your Flask app instead
Unfortunately I've only actually used nginx for my Django app so I'm not really familiar with the configuration
DigitalOcean seems to have an article about Flask and Apache, you might want to look around though
https://www.digitalocean.com/community/tutorials/how-to-deploy-a-flask-application-on-an-ubuntu-vps
Right, that's as far as I can go in terms of Apache, again, I'm not as familiar with it as I'm familiar with nginx
You could try routing
You should use mod_wsgi for Apache
Heyo how could I host this on my website https://github.com/AlexFlipnote/TypingTest
Would I need a vps?
Or just cpanel
No, no. I mean I am running a website (just html, css, php, javascript files) using Apache. How can i run a flask app on the same server for the same domain but like domain.com should take to my normal website and domain.com/flask should lead to flask app?
@native tide you can just follow that example. Put your flask directory in thatDirectorydirective.
Heyo how could I host this on my website https://github.com/AlexFlipnote/TypingTest
Nope?
That's what Directory directives are for ๐
If your site is at /var/www and your flask app is /var/www/flask, you can just add a Directory /var/www/flask section
Yeah
Could anyone help
Well then, use /var/www/domain.com/flaskapp
No, you just need to enable mod_wsgi and configure it.
Could anyone help
@novel pawn clone that website, thenpip install -r requirements.txt. Then you can execute thestart.shscript given
Would I need a VPS or is cPanel fine
you can do it in your local computer, why would you need a vps
Could anyone help
@novel pawn Look at thestart.shscript. you will probably need to add a ngnix service for it.
Django: How do I unlink images that were uploaded to my disk? Suppose I delete an object of PostImage, how do I delete the actual image.png that would be stored in the disk?
Do I have to do that manually?
Note that when a model is deleted, related files are not deleted. If you need to cleanup orphaned files, youโll need to handle it yourself (for instance, with a custom management command that can be run manually or scheduled to run periodically via e.g. cron).
Maybe handle it in the pre_delete signal?
That kinda sucks
but I see how that would be useful
Maybe I will have to write a py script to recurse over the directories and delete unlinked files
It imports the variable app from the file named yourapplication.py and renames it to application
should i design the api first or plan the react front end before that?
Iterate and do both at once ๐
I usually just add a basic page, with fake data on the front-end. Then add an API call.
Iterate and do both at once ๐
@lethal orbit expected easier answer lol
Hook up the front-end to the back-end, then work on another feature.
You don't need to spend too much time overdesigning an API ahead of time.
Sometimes I do it the other way around.
You can just call the API using curl for REST, or graphiql for GraphQL. It really doesn't matter.
(yes, there are tons of other options I didn't bother listing).
@lethal orbit nice man thanks.
@lethal orbit In my var/www/domain.com/flaskapp what files should I have for example for a hellp world program?
@native tide I don't really use Flask, and never have with apache, but I think you need one file for your app, and one.wsgifile.
Are you on the same machine as Flask?
127.0.0.1 is localhost
Then you can't use Firefox.
127.0.0.1 is your machine.
You can use curl on the server.
curl http://locahost:5000 should work, if you open a new SSH section
No, it's not bound to the public IP
On the loopback interface ๐
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
flask run --host=0.0.0.0
or use app.run(host= '0.0.0.0')
You need to bind to the public IP.
0.0.0.0 binds to all available interfaces.
any advice format docuement tool for django html
Yes
If you run flask locally, localhost should work.
add ``` before and after``` your code... (to make it readable on discord)
The rest looks fine.... though I think you are missing a () in app.run()
can anyone tell me why my <script type="text/javascript" src="{{ url_for('static', filename='jquery-3.5.1.min.js') }}"></script> only works if I have it in my template that uses the script but wont work if i have it in the layout.html which is extended in the same page?
do the scripts have to be loaded in a specific order?
wait, now it suddenly works both ways.. wtf nvm
no, it's back again
if I put it in the end of layout.html, jquery wont work