#web-development
2 messages · Page 74 of 1
I wanna know how much a quora clone in django can cost, and how much an ecommece website costs, I mean if I wanna make one how much I can sell it for
@flint breach I am asking you cuz you may have a lot of experience in freelancing
i work at a company, so i wouldn't really know
never worked as a free lancer
but a question of how much can a clone of "X" cost can vary highly
first of all, depends if there are buyers interested
second, you can make a clone of instagram
but it's not really...like instagram if you know what i mean
Ehh, i couldn't tell you, i don't know myself
as i've said, don't have freelancing experience 😛
is it hard to make one
depends on what scale
@late fjord i have already done all that
@flint breach i have put an extend i didnt show the full code because i didn't think it was necessary
how do i do that
hmm
this is annoying
when i go on the webpage and inspect element it appears but it has no affect
oh, then it has loaded sucesfully
probably something got overwritten in the css hierarchy
Hi!, I have question, how can i get content error message from my response when i have 500 status code? I Wrote my midlleware for this action but in response.content i have all html code with error and in response.reason_phrase field i have only short message Server error
class LoggerMiddleware:
def __init__(self, get_response=None):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
if response.status_code == 500:
print(response.content)
return response
Easiest way to deploy flask app with mysql db on apache linux server ? I never did that was working on heroku and AWS in general..
@modest scaffold try this {% block 'head' %} #put your title and css link here, make sure it is above the other one {% endblock %}
@modest scaffold instead of block title and block addition....
ok will try this later ill keep you updated if that okay
totally fine
imagine we have two apps, we want to use the same main template on both apps in django, please help
@flint breach that cant be the case because im not overriding anything
well i dont think i am
check in dev console
either it's cache or that, since you said you checked and it's on the site
the css file
developer tools are your friends
@modest scaffold it didn't work ??
is ASP Core something that's worthwhile to learn?
i havent tried it yet bc im a bit busy with something else
Beachtastic, only if you want to do more C# development
i figured. i just wasn't sure if it was something i should actively try to learn since idk what the trend is atm
If you know C# and want to continue using it, it’s very nice.
ASP and Javay Springboot stuff only seem worth it if that's what you gotta do for a job
im casting a wide net at this point (career-wise), so i think i'll do a small project on it to get familiar with it lol
We build rest API at work with it for our Angular front ends
Flask:
How can I specify an API key inside init and use inside routes?
Key will update every so often, so I would rather create it inside init which is pretty empty
### init
api_key = '11233'
## routes.py
uri = 'domain.com/apikey={keyhere}'
Django:
Do I have to create a template file in each django app?
@mellow briar @modest scaffold @flint breach @native tide
don't ping everyone please
yes
just ask your question, you'll get an answer
you do need to create a template file for each app but you could do one main template file
you don't actually
and dont ping people unless they're engaged in the convo
yes
depends on what you need
yea
it's just a convention, of course it's prefered that unique templates of an app go into the app directory
but something that's shared throughout the project can be in a shared template directory, so to speak
thanks
what do you mean by a "template"?
an html file in django I guess
no
you only need to do that if you will be rendering that view
do what
if you are building and API with django rest framework or graphene geaphql (or other similar framework) you will not need to write html code
which is the recommended
to separate front and back end applications
not really recommended, a different style definitely (SPA and the like)
its more scalable tha monolotic applications and expansible to mico service integrations
but anyway, idk waht the ideia of the mate here
most people don't really need something to be google scalable
i guess you shoud take a look of how these things works together
django scales well
I wouldn’t use Django for RestAPI unless you already have Django site
I don't what you guys are talking about cuz I haven't gone through these details yes and the rest freamework
thats a matter of point of view. These was mine, im getting back to work here, so good study yall 😄
Look at Flask or FastAPI instead
I have been using django for a month and a half maximally
I wouldn’t use Django for RestAPI unless you already have Django site
@zealous siren disagree
or maybe not, depends 😄
Django is heavy, Rest API are not. No need for all that weight
If I want to create a website where you can post, ask questions.
Is it good to put them all inside one app called app
Or maybe put posts inside and app and questions in another one
Django for a rest api gives you the advantage of a phenomenal ORM
it's annoying that it comes with the rest of the Django baggage though
someone should figure out a way to add the Django ORM to FastAPI
then FastAPI would be the best tool going
@rigid laurel please answer my question
ye, django is not the only ORM
you can put it all in one app, if it ties togheter well
if it makes sense that it's togheter, put it togheter
but which is better
either is probably fine. I would lean towards more apps
SQLAlchemy is rubbish compared to Django's ORM
hard disagree, SQLAlchemy is great
Django's ORM blows SQLA out of the water in terms of usability
Tying together Flask+FlaskSQLALchemy+Alembic+Marshmallow to get a Flask API going is just a massive PITA. Someone combining all of that to make it more cohesive would be so much nicer
lol the reason they exist separately is to give you a choice of implementation
if you like all those tools together just make a project template
☝️
I personally like stitching the tools together because it gives me a nice IKEA effect feeling https://www.psychologytoday.com/us/blog/the-shaping-us/201910/the-ikea-effect
I hate the ikea feeling - and I guess the cookiecutter stuff is a goodish solution. But my experience with Django's ORM is that it's nicer in almost every single aspect, and having a single source for information about the entire system (i.e the Django docs) makes it so much easier when you're not super experienced with all the parts
having a single source for information about the entire system (i.e the Django docs)
SQLA also has docs
SQLA's docs are not what I'd call good examples of documentaion
just looking at something like m2m relationships, they're so much easier to deal with in Django
https://docs.sqlalchemy.org/en/13/orm/basic_relationships.html#many-to-many seems pretty clear to me 👀
meh, down to preference i think
if you're not gonna use django, then it's orm is outa the question anyway
🤷♂️
true, I don't like that django hides the implementation details
to each his own, i love that, (when im doing most things)
but when i have to customize something or extend it, that abstraction can definitely become a real pain
then again, python is C with hidden implementation details 😛
Sounds to me like you like doing work for the sake of doing work
I can understand a database schema from a theoretical perspective, I don't necessarily feel the need to get too close to the actual SQL though
Django hiding a link table from me is fine in my books
when writing deep nested/complex queries though, that's when the orm is a pain in my ass
(Especially since you can make your own link table, there's just no need unless you have more fields to add https://docs.djangoproject.com/en/3.0/topics/db/models/#extra-fields-on-many-to-many-relationships )
I like knowing how my ORM is querying my tables. I have experience with SQLAlchemy and how it works so I like it, I'm sure I'd like django's orm the same once I got to know it, but the docs don't seem to expose how they're querying the data
under every query you make, django exposes a query attribute to every queryset you make, that's basically the constructed sql statement
it's preety sweet
that sounds nice
I've heard bad things about ORMs and complex schemas - but right now I'm lucky enough to never have dealt with a complex schema outside of raw SQL itself - so I guess I can't speak for that too much
But Django's model of querying feels much more natural/expressive than SQLAs way
agree with simple queries, strongly disagree with complex ones
been too long since I touched either to give a specific example
but I really feel like for most standard enterprisey schemas - Django is fine
if your system is big enough that complex schemas are a problem - then I think I'd be sick of Python as a whole and just want to redo it as microservices or in Kotlin
agreed tbh
that sounds like trading out one set of problems for another to me
well - rebuilding a system is rarely a solution yeah, but starting off in Kotlin seems like it would be much better
in general though, trading out one tool for another is just switching the problems you'll have
mongo vs sql, django vs flask, GCP vs AWS
ehh, relational vs non relational solve completely different problems
not really, most dbs can switch them out without much difference
if you have relational data, then yeah, don't use nosql
oof, strong disagree, completely different scalability setups, sharding and fragmenting is trivial in nosql, redundancy difference, CAP, data schemes itself
Mongo vs SQL seems pretty clear cut to me
this is what I mean though, sql vs nosql can be swapped out for most db schemas, you're just trading the problems (you listed administration, but schema setup and query optimizing are also some problems you'd trade)
Postgres has Citus for scaling
The solution to every problem seems to be Postgres
I don’t use Postgres
Well - you live in Azure land right?
Yep
and I'm guessing MS have some proprietary thing
They do
MSSQL+scaling fun
Is there a way to user https://django-filter.readthedocs.io/en/stable/ with ajax?
what do you mean?
Like, I want to use django-filter with ajax in vanilla django
im still not sure i follow
you can filter in with regular querysets, and before you serialize to deal with api requests
you said you're using ajax
No
I'm mixing templates with some api-ish endpoints
you're not recieving models, you're recieving json data
if you control the api endpoints, you can use django filters to sort
but then again, don't know if you need to
hey all -- trying to verify a password input against db entry however it always returns "The password does not match the supplied hash". I use argon2 against the input with the same parameters as the first except the salt, since argon2 by default randomly salts each time, thus the two entries never matching. Should I be using the same salt, or am I misunderstanding how the verify function works? I thought this may be the right channel (since it's webdev related), however if I should move this to security instead pls let me know! If any additional info is needed I'll gladly add to this. c:
using py3.8, tornado, mysqldb and argon2id.
The salt should be the same
I'd like to close window after oauth2 with flask, can I do that?
javascript can't :/
hey all, i'm using flask to process data from a post request from ajax in JS script, how do i process lists?
i'm sending the list like this:
weblogs: automodWeblogs where automodWeblogs is an array of JSON objects (because this is in the JS code)
i'm processing the data sent by using request.form but i've also tried request.form.to_dict().
Whenever I print out the data i receive, it prints in a form like this:
'weblogs[0][user]': ['MrHouck#6969'], 'weblogs[0][time]': ['Sat, 25 Jul 2020 17:36:29 '], 'weblogs[0][action]': ['automod.bannedWord.remove'], 'weblogs[1][user]': ['MrHouck#6969'], 'weblogs[1][time]': ['Sat, 25 Jul 2020 17:36:29 '], 'weblogs[1][action]': ['automod.bannedWord.remove']
How do I fix this?
the issue being that it's formatting like [weblogs][0][user] whereas it should be like weblogs[{'user':'MrHouck#6969', 'time':'Sat, 25 Jul 2020 17:36:29 ', 'action':'automod.bannedWord.remove'}]
@flint breach thanks for the suggestion, appreciate the help; while that would work, I went back to the docs to reread (thought maybe I did misunderstand) and turns out the verify function of a2 uses the stored salt from the hash when comparing against the input, so there's no need to hash the input from the form, as it does it on it's own.
hello guys
say the above was in a different file
__name__ would be different right?
if I do tracer = trace.get_tracer("__main__") this also returns None
even though it has been ran before in manage.py
how do I share this tracer?
can anyone tell me what:
Can't instantiate abstract class TracerProvider with abstract methods get_tracer
means?
why is that happening
can anyone tell me what:
@proud igloo you have to implement the method get_tracer, or extend that abstract class and implement the method.
Abstract classes are not meant to be instantiated (hence the creator defined the class abstract).
but when I called it before it worked fine!
that is what I am so confused about
in def main():
I am trying to copy this example
what is the difference between putting it in a main and putting at the top of an imported file?
if __name__ == "__main__":
main()
def main():
Yo
You can do that, but it is a little silly, why not just put whatever you were gonna put in main() in that if statement
the reason behind this is so that variable within the main block does not get put in the global scope.
Hello everyone
hey, I was wondering what was Apache and Nginx, i saw few people talking about it in #cybersecurity, if I want to deploy my Django Rest API, how do I do that?
for example I am just doing this:
jaeger_collector_host_name = os.environ.get("JAEGER_COLLECTOR_HOST_NAME", False)
trace.set_tracer_provider(TracerProvider())
if not jaeger_collector_host_name:
# print tracer
trace.get_tracer_provider().add_span_processor(
SimpleExportSpanProcessor(ConsoleSpanExporter())
)
else:
# jaeger tracer
jaeger_exporter = jaeger.JaegerSpanExporter(
service_name="App",
collector_host_name=jaeger_collector_host_name,
collector_port=14268,
)
trace.get_tracer_provider().add_span_processor(
BatchExportSpanProcessor(jaeger_exporter)
)
application = get_wsgi_application()
application = OpenTelemetryMiddleware(application)
and I get
TypeError: Can't instantiate abstract class TracerProvider with abstract methods get_tracer
TracerProvider isn't meant to be instantated by itself, it is an abstract class
you need to use a subclass of TracerProvider
so my guess is the docs are outdated
Oh wait looks like there is two different things called TracerProvider in two different places
what do your imports look like
@proud igloo
from opentelemetry.sdk.trace import TracerProvider
is that wrong?
ahh!!
that was it
thank you so much!!
i'm trying to make custom error views in django
i'm settings the handlers in my urlconf
and i have DEBUG set to False
but whenever i go to a page that would give me a 404, it's using django's default 404 view instead of using the custom one that i specified
i'm setting the 404 view in my urlconf as this
handler404 = "uploader.views.err_not_found"
and the view is
def err_not_found(request: HttpRequest, exception):
payload = {
"message": "The requested resource was not found on the server."
}
return JsonResponse(payload, status=404)
i see no reason why it's displaying django's default 404 view
instead of using the one i provided above
is it possible to get a BLOB image data from sqlite and display the actual image? Using flask.
I have the image blob data saved in the database, but am clueless how to show it back to the user
When i try to show it on jinja, it gives me this weird b"
Also by the way, the user can upload the image and it is saved in my static directory
hey, I was wondering what was Apache and Nginx, i saw few people talking about it in #cybersecurity, if I want to deploy my Django Rest API, how do I do that?
@twilit zenith they are web servers, the things that actually run your code
@distant trout It seems the image is base64 encoded. Just look up how to encode/decode base64 in Python
for a flask app in an AWS VPC, is there an easy way to enable CORS for any other application hosted in the VPC?
is it as simple as allow * and the VPC does the rest?
Howdy friends, I have a Django app/api. It especially has blog posts, but these posts need to maintain their formatting (i.e tabbed lines, spaces, line breaks etc.) So it should be as easy as writing the content in microsoft word, then pasting the result in a text field. this data needs to then be sent via api. Any ideas on how to accomplish this?
markdown?
Ty, I answered my own question. I was using markdown, but it was unreasonable for the user to know how to use it.
I realized the <pre> tag in html is made just for this and django/django rest api preserve this formatting, so the only solution was on the front end.
I have a flask app up and running on Heroku, using gunicorn
How do I serve static files?
look for s3
I read about Nginx/Apache/Amazon S3, do they do the same thing?
Nginx is free whereas Apache/S3 are not?
Apache/Nginx isnt for static files right?
Is anybody out there
what is the equivalent of django rest serializer source attr in flask marshmallow?
If I have a rest API in DRF that allows users to join events, what would be the best way to not allow any more users in an event when max capacity is reached? A validation method in the serializer class? Or is it better to have a check in the create method in the modelviewset class? Or in the models?
what is better when it comes to performance?
flask or django?
make sure your test modules/packages have valid python names
im getting this when running pytest
Flask is more lightweight in general, better for performance. But it also heavily dependns your programming.
the file name for testing is called test_back_end.py
can anyone help me out?
@acoustic oyster for dashboard for my discord bot, what will be better?
A small flask project will be generally "faster" than a small django project.
But if it is a very small project and it is for personal use, you will pretty much not see that performance difference.
If you want to use a database, django will be easier to set up imo
For reference: I was accidentlsly spamming api requests to my django site in a recursive loop earlier and I only noticed because of the logs. The site performance barely changed.
Are there any other free alternatives to amazon S3 to host static files?
Don’t think it matters but I’m using flask and deploying to Heroku with gunicorn
S3 is pretty cheap. GCP also has storage buckets where you get some amount of stuff for free
Ohh I’ll look into Google Cloud thanks
Most blogs with just images won’t use that much storage anyway right?
So it’ll be like less than $1
On S3
yea, s3 itself is dirt cheap
s3 gives you 5gb of storage and a fair amount if ingress/egress for free - the only thing you might have to consider is actual malicious attacks, people spam requesting from it or something
Hey guys, random question, if I use requests..post to send data to a server that I want to be modified, e.g. sending two numbers asking the server to multiply them, how do I get the response back?
you need to set up a web server that will listen for the incoming request, process the request to do whatever, and then return the result
the specifics of that can be done in a million different ways
one way would be to set up a very simple Flask app
Got it, any decent resource I can read to implement this?
It really depends on how much you need to do yourself and how much can be done for you
for real though, perhaps to understand it, use something like flask to implement it, which is simple
what is the actual task?
writing an actual server and such isn't trivial, much less so if it's production grade
Yeah, setting up Flask to be production grade is very annoying for this task
I havent used python for web dev before so literally what I want to do is setup a server that I can ping with numbers and then it returns them multiplied
for a quick+simple test, it's not too bad
Typically Python isn't the actual server though
(based on this I will upload my ML algorithm which is more difficult but want to start here)
I am using GCP for some more computing power so I dont have to load in my huge ml model on my compute
well look into the sockets module, http refrence, and other computer networking resources if you're gonna do it from scratch
if you jsut want the functionality, look into flask like he said
so its only for myself and doesnt need to be production grade
Honestly, this task isn't that connected to the ML deployment stuff. If I were you, I'd just jump straight into trying to deploy the ML algorithm
Okay, my end goal is essentially to use a VM on GCP where I will host my ML algo that I can then query
thought that was more or less analogous to the VM running a server that would respond to requests
hence why I was doing it this way, but very open to do this another way
I'd do that if I were you
agreed, ^
for some reason i changed my code a bit and the css file got loaded
could someone check my code to see if theres anything wrong i was doing
post it
k one sec
this was my question the difference are in the question
so it works now?
def WorkFour(request, *args, **kwargs):
form = CreateAdvertisement(request.POST, request.FILES)
user = request.user
teste = user.ads.all()
if len(teste) == 0:
if form.is_valid():
instance = Advertisement(**form.cleaned_data)
instance.check()
instance.user = request.user
instance.save()
return redirect('anuncio:w5')
else:
if form.is_valid():
form.save()
return redirect('anuncio:w5')
context = {
'form': form
}
return render(request, "trabalhe_4.html", context)
@flint breach yup
I'm trying to update this form in django, when It's used the else condition. It's not working, can anyone help me? Thanks in advance
In a flask app
If I want to add a multiple choice quiz to a blog post dynamically created on the website
Do I just do it with <script>? So I mix JavaScript code in my blog post?
hey im not sure if im asking in the right channel but i am very new to python and need some help. I am trying to print as shown in the image, provided with a list. im stuck on how to even print out the pattern, someone please help 😭
world_map = [['T', ' ', ' ', ' ', ' ', ' ', ' ', ' '],\
[' ', ' ', ' ', 'T', ' ', ' ', ' ', ' '],\
[' ', ' ', ' ', ' ', ' ', 'T', ' ', ' '],\
[' ', 'T', ' ', ' ', ' ', ' ', ' ', ' '],\
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],\
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],\
[' ', ' ', ' ', ' ', 'T', ' ', ' ', ' '],\
[' ', ' ', ' ', ' ', ' ', ' ', ' ', 'K']]
Anyone has experience with cPanel hosting ?
The client doesnt have terminal so i really dont know how should i handle the db changes. i can push migrations folder but how can i acheive anything without dropping the table eacch time something new is added
Is it better just to use Django for everything or should I for example use Django for backend and reactJS for front end?
I'm trying to update this form in django, when It's used the else condition. It's not working, can anyone help me? Thanks in advance
@formal shell is this used only for post?
@formal shell is this used only for post?
@flint breach Yes, it is my friend
the else looks valid
is it a model form?
also looks like the code could be cleaned, a bit, perhaps overwriting the form.save() to handle additional logic there
it's not, you missed it
Hello, I am trying to use Flask to create a website, but I'm a little confused with main not being a resolved reference in the below code:
app = Flask(__main__)
It works when I replace "main" with "name" but then I'm unsure on what to do next because I'm not sure how to tell the app to run
is it a model form?
@flint breach Yes, it is a model form, and this problem occurs when I click submit in the form (NOT NULL constraint failed: anuncio_advertisement.user_id).
this is with the else?
@merry geode
@distant trout It seems the image is base64 encoded. Just look up how to encode/decode base64 in Python
Thank you!
this is with the else?
@flint breach Sorry for taking too long to answer, but yes. It's happening specifically because of the form.save()
Are you checking the form is valid by calling .is_valid() first?
@formal shell
@native tide app.run()
And name is the name of file , main is the file that imports your current file
This might be the wrong place to ask, but I'm creating a single page application with Flask. Is there a way to dynamically change the page content while keeping the url static?
You'll need to use AJAX
And there are some ways to change the url without the page reloading
Thanks rader
np
Are you checking the form is valid by calling
.is_valid()first?
@formal shell
@rigid laurel I forgot to pass an instace to my form.save(), now it is running ok.
Thanks for the help guys
@login_required()
def WorkFour(request, *args, **kwargs):
form = CreateAdvertisement(request.POST, request.FILES)
user = request.user
form_update = CreateAdvertisement(request.POST, request.FILES,instance=Advertisement.objects.get(user=user))
teste = user.ads.all()
if len(teste) == 0:
if form.is_valid():
instance = Advertisement(**form.cleaned_data)
instance.check()
instance.user = request.user
instance.save()
return redirect('anuncio:w5')
else:
if form_update.is_valid():
form_update.save()
return redirect('anuncio:w5')
context = {
'form': form
}
return render(request, "trabalhe_4.html", context)
That`s what I did
Hello i am thinking of starting web development with django how can I start what are the pre requisite of starting django
have pip installed and scripts on PATH is the only one. django is on pypi
@dapper raft YT tutorials are good for beginners , documentation is nice too though!
@dapper raft Flask is better imo tho!
Like it's much much more flexible
It's lightweight
And you can just organize your code so much more
It depends on your needs
Well , you can make the same websites with both
Oh true. Just like you could make the same website going with bare python and 0 framework
I wnt to make simple blog
Then you can choose either of them
Where I can fetch data from an api
flask is not async, and django is only sort of async
Based on your needs as @dapper tusk said
if you want async, there is a flask like thing that is fully async afaik
Yes I wnt async
I'd rather flask anyways . You can do everything Django does with it's libraries
But still
Actually I will use one module to fetch data from api
Oh
It fetches data from game api
@glass sandal You're saying that just because you're much more familiar with Flask, that's not objective
@bleak bobcat I learned Django first
Doesn't mean you're more familiar with django
Well what market demands
But I've seen more websites for django tutorials than flask
He says he wants async and you answer with flask...
I am more comfortable with Django models too
But I use flask
And async could be done using third party libraries
Sure, you can use some async inside flask, but at the core it's still sync
Guys one more thing I wnt to take in consideration I wnt to learn framework which market wnts
Ok thanks buddies
Django is not async yet, it's comming but for now it barely has some async functionalities
@bleak bobcat So it's better using flask until that version thing comes
And @dapper raft np
Or FastAPI which is basically async flask...
Well , didn't know that framework
But he/she wants a framework that market wants too
Well market is not ready for async...
So he/she either has to choose Flask if async is so important or django if the market side is much more important
@bleak bobcat But he/she needs to learn a framework that he/she can use too!
!ban 695267216102391868 joined just to tell people to die
:incoming_envelope: :ok_hand: applied ban to @hollow jay permanently.
I mean , Django is good too
But you know , when project gets big , you need flexiblity
Quite the opposite imo actually
When project gets big you need a structure everyone knows
That's for open source projects
Or company projects
a structure that you and your team understand is much better
There's nothing worse than working for a company for some time and leaving with only having learn their way of doing it
Will be applicable nowhere else
Well , for company projects just use Django . If I were to choose a framework for me and my team(If I had one) , then 100% flask , nothing else
Wait
lemme edit it
Again, depends on the project...Small project ? Sure, go flask
Flask is used in big projects too :/
It's small enough that everyone knows where everything is
Well , just use Django's structure
You don't have to have all your functionality come from one library
flask + other libraries can do everything django can
Yeah
Well , just use Django's structure
So you're building django...on top of flask ? What's the point ? Wasting time ?
Other functionality or better working functionality than is available in django
Yeah
django is great, but there are reasons people would want to use flask instead
When you use Django's structure , it doesn't mean you loose flexiblity
in a production enviroment
Yeah exactly
As I said , the market wants Django , despite all the cons . But as I said , you want to freelance or work in a company? Django . You have a team or you are going to develope a website yourself? Flask
In Django Rest Framework, how do I get the object from a url when I have HyperlinkedModelSerializers? Even the pk would be fine, but I don't seem to find a way that seems intuitive
obj from an url?
if you want the an object directly use https://www.django-rest-framework.org/api-guide/relations/#reverse-relations
Django, API, REST, Serializer relations
Flash and Django are both python web frameworks so surely learning one of them is going to make the other one easier.... Right?
So I can just learn Django then in the future if I want/need to I can pick up flask easier
some concepts definitely apply so yea
routing, templates etc are all shared traits
as long as you pick up concepts, switching frameworks is a lot easier yea
Hey, good afternoon guys. I have a question. What should I know in Python before getting into Django? I really want to get into Django.
Probably as much as possible tbh
Fair enough.
django is a python framework, i imagine everything helps like he said
a lot of magic implementation details are hidden - metaclass magic to define how django objects (database objects) function
a lot of things like that, that you don't need to know, but if you do, it'll make you a better programmer overall
Alright, cool. I wouldn't say I'm a pro with Python by any means but I have been able to get basic things going with different libraries and I feel I have a decent understanding of it. Classes, objects, loops, vars, data types, stuff like that.
I'm going to go through the Django tutorial, it looks good.
Are there any tough things with Django I should lookout for?
Nope , django is very easy and u wont do too much backend . most of stuffs django will handle it
i highly recommend watching Corey Schafer
That is awesome. Hey this guy has helped me learn a lot, he's got a lot major stuff. He helped me understand classes and objects, he explains really well. I will check this out.
Ofc Corey is someone very special. Glad you are excited 🙂
anyone have experience with creating an oauth2 client with python?
does anyone know how to make a button so when someone clicks on it it screenshot the current page and download it with the company's logo like this
as there is down the company name which is miro so i exported the page into an image
Question
urlpatterns = [
path('', views.index, name='index'),
]
How does this code work? I know it pulls the view index but how do I specify a URL to route to a different view?
my urls.py folder contains this
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
And when the server gets polls/ it pulls up the index view
but how do I specify a different view to access if I wanted to add a new path like home/
if you want wesite.com/home/ you want to add it to the project urls.py, if you want to have wesite.com/polls/home/ you put it in the polls app
include means all paths that match the pattern get routed to 'polls.urls'
im creating a ubuntu django server and my question is should i develop my project in the server or outside? it my firs time with a server, normally i just code localy
I would suggest locally so that you get code reloading from runserver
if you want to have it as a separate app, make it a separate app, you could also make it point to a view directly @fiery coral
@quiet comet I think this helps you. This is from the Django tutorial.
Where should this code live?
If your background is in plain old PHP (with no use of modern frameworks), you’re probably used to putting code under the Web server’s document root (in a place such as /var/www). With Django, you don’t do that. It’s not a good idea to put any of this Python code within your Web server’s document root, because it risks the possibility that people may be able to view your code over the Web. That’s not good for security.
Put your code in some directory outside of the document root, such as /home/mycode.
how do I make it point to a view directly
@dapper tusk
the same way you made it point to a view in an app pattern
@flint breach I have set up reverse relations already.
Can you specify what you mean exactly then
So I have a user that is trying to subscribe to an event. The event is a foreign key attribute of the user. Then, when creating a user I want to check if the event is already full or not
Then, when getting the serializer data in the viewset perform_create method, I get a url for the event, because my EventSerializer is a HyperlinkedModelSerializer
but I want to get the event object, as I want to check 1) what is its capacity and 2) how many users are already attending
Im gueesing hyperlinked is not the right serializer then
and the step I am missing is how to get the event object from the url that I get from the post data
I think there has to be a way
I mean the point of the hyperlinked one is to for example show the links of all the related items in a gui or something not to get the ovjects themselves
my question was should i code in the server(which is a VM) or outside( my pc, windows), i think im going to code outside and after im done i will copy to the server so it will be deploy.
@quiet comet Yeah, I misread that.
Django, API, REST, Serializer relations
@native tide
Use a nested serializer is my suggestion
@flint breach interesting, I will look into that, thanks!
when i try to import a model from my models.py file
like this
from .models import Subscribe
i get no error
but when i try it from another file
i get this error
ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package
this is what i am doing
import smtplib, ssl, os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from .models import Subscribe
sender_email = os.environ['SENDER_EMAIL']
sender_password = os.environ['SENDER_PASSWORD']
recipients = []
for i in Subscribe.objects.all:
recipients.append(i.email)
print(recipients)```
I am using Django btw.
Is the file youre importig in, in the same directory?
yes
d----- 7/28/2020 2:15 PM migrations
d----- 7/28/2020 8:43 PM static
d----- 7/27/2020 6:26 PM templates
-a---- 7/28/2020 1:35 PM 125 admin.py
-a---- 7/27/2020 6:23 PM 98 apps.py
-a---- 7/28/2020 7:36 PM 253 forms.py
-a---- 7/28/2020 2:15 PM 490 models.py
-a---- 7/29/2020 4:09 PM 1431 send_data.py
-a---- 7/27/2020 6:23 PM 63 tests.py
-a---- 7/28/2020 5:48 PM 159 urls.py
-a---- 7/28/2020 5:52 PM 1015 views.py
-a---- 7/27/2020 6:23 PM 0 __init__.py```
why i use ls i get that
Unfortunately my phone view of this is horrible
and in the send_data file i try to import models
ok. models.py and send_data.py are in the same dir
Alright, can you specify fro@ which line the error is coming from
import smtplib, ssl, os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from .models import Subscribe # This line
sender_email = os.environ['SENDER_EMAIL']
sender_password = os.environ['SENDER_PASSWORD']
recipients = []
for i in Subscribe.objects.all:
recipients.append(i.email)
print(recipients)```
@flint breach I am gonna for the nested serializer it fits exactly what I need, thanks! One last question, what is the better place to do the validation for whether the event is full, as a field validation on the serializer or as part of the perform_create method on the viewset class?
Tbh wouldnt know till i see it, as long as it makes sense where it is, and stays DRY, you should be alright
import smtplib, ssl, os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from .models import Subscribe
sender_email = os.environ['SENDER_EMAIL']
sender_password = os.environ['SENDER_PASSWORD']
recipients = []
for i in Subscribe.objects.all:
recipients.append(i.email)
print(recipients)```
@native tide what happens if you do an absolute import
Not sure whats causing the error
from .models import Subscribe causes the errorr
Yea i know, does an absolute import cause the same error?
no
i did import subscribe.models
and got this error
ModuleNotFoundError: No module named 'subscribe'
From subscribe import models?
if i do that
i get this error
ModuleNotFoundError: No module named 'subscribe'
👀
You need to specify thr full path from the root of the project
@flint breach in the example from nested serializers from the docs (https://www.django-rest-framework.org/api-guide/relations/#nested-relationships) we have album and tracklist. When viewing the album details, we see the nested track objects info. However when viewing the track info, we would see only the album id. Is there any way that we can also see the nested album info in the track detail view without it being infinite nested? Maybe a second serializer class only for that purpose...?
Django, API, REST, Serializer relations
Hey does anyone know how I should go about indexing a nested dictionary that is returned by a 3rd party API.
foreach your way through it?
I can do it that way but the data it returns needs to be saved in multiple spots. It’s returning a shipping label so I can’t run the method multiple times or it will create a few identical shipping labels.
you talking something like this: json { "index1": {"value2":"item1"} }
exactly
test to see if you already have the data
I have the data but it gets returned from a POST request
You just use a different serializer in that case, with a reverse on the album, whichs serialized the data u need
Hamwallet, I'm too confused
'Response': {
'ResponseStatus': {
'Code': '1',
'Description': 'Success'
},
'Alert': [],
'AlertDetail': [],
'TransactionReference': {
'CustomerContext': 'Customer Context',
'TransactionIdentifier': None
}
},
'ShipmentResults': {
'Disclaimer': [],
'ShipmentCharges': {
'RateChart': None,
'BaseServiceCharge': None,
'TransportationCharges': {
'Code': None,
'Description': None,
'CurrencyCode': 'USD',
'MonetaryValue': '16.52',
'SubType': None
}
That is part of what is returned from the api
I only need to save a few specific portions of that data to a model but I can't run the POST request more than once
@flint breach problem is that then it interferes with the creation of tracks in that case, as the album field gets messed up for the POST request
I guess then you need to customize the creation method to use yet another serializer (for track in this case)
you have the data
response['response']['shipmentresults']['shipmentcharges']['RateChart']
yeah i just realized that, thank you
I tried that and now I am getting an error saying that list indices must be integers or slices, not strings
the data that is returned isn't a list however
just figured it out, there was a list nested into the dictionary as a value
Hi, so I had a critical incident in heroku, how can I see the logs for it?
I am able to see it through the metrics tab
A timeout
I wanna find the logs for it
It is probably caused by a bug I have been hunting for weeks
do you have a place you're sending logs?
No, I don't. I don't usually use Heroku, client wanted :X
Do you have any idea on how I could store logs
and find out what that bug is
there are probably some logging addons for heroku you could add
I use AWS elasticsearch service and send logs to it using https://github.com/cmanaha/python-elasticsearch-logger
I use aws as well
AWS elasticsearch service has a free tier
yeah it's just an easier layer on top of AWS
so it's nice to get started or for small apps
I usually use docker/k8s and an EC2 instance
k8s on GCP?
right, but kubernetes is not
Kubernetes is supported
AWS ECS is the AWS version of it if you wanted them all in the same place
It is actually rly nice
Basically, using anything other than Heroku was a dealbreaker for my client.
RIP
Is that just because they dont know of any other service tho lo;
No damn idea
I asked them and they replied cause I like it more and I was like: you do you
How do I deploy my flask app? I am currently using: https://pastebin.com/x9Bcfgrj, but it deploys to localhost
how would I deploy it to be available?
gunicorn is one of the most common methods
good evening everyone, in my django project I try to integrate sentry, but when launching travis it tells me ModuleNotFoundError: No module named 'raven'. however in my requirements.txt I have raven == 6.10.0. and I can't find a solution ... even on stackO
any resources on how I would be doing that?
You can already access your website through localhost?
You just need to port forward then
can someone suggest the simplest way to maintain the aspect ration of an image in django? The built in ImageField apparently cannot read meta data, so all images become landscapes upon uploading.
You'll need to get the metadata somehow, so I suppose that means a third party library
ok, that is what I am seeing. I see django has height_field() and width_field() But it is unclear to me how to use these
You're talking about EXIF orientation, right?
If so, I wonder if you can subclass the field and create one that supports loading EXIF metadata with a library
And you could use some CSS to transform the image based on orientation if you plan to display it.
Assuming you want to preserve the image as is. The other option is to just rotate the image and re-save it
I am using a JS library that uses the aspect ratio to display the images.
I mean, the lazy way is to add an option for portrait or landscape LOL,
I'm just surprised this is not built into django, it seems like a common task
and yes
I need to tell my js if it should be displayed in portrait or landscape mode, but django makes all images landscape 😢
ill make my user explicitly say if it is portrait or landscape pats self on back
I'm still not sure if you're talking about EXIF orientation or not
well, the issue is any image that is taller than it is wide is perceived as landscape as well as any image that is wider than it is tall.
This is for uploading art, but the result is stretched images that do not fit.
I am unsure where exif applies, but I assume yes
well, my app uses the django api to get the image urls and the aspect ratio. But the width is always the largest number and y is always the smallest number.
I need the user to be able to upload an image, save the original x and y dimensions, then include those x, y dimensions in the api with the url so that the React app can load them in
the issue is that the default dimensions are always width == max(width, height), height == min(width, height
for all image files, both pictures from android and iphone and also drawings in png, jpg format from photoshop or other drawing related apps.
I am finding very few similar issues online
Is it only the dimension attributes that are wrong, or is the image itself modified too?
Like, if you open the URL in your browser, does the image look fine?
sorry, SOME images are fine, some break.
one sec, lemme test that
hmm, well. It is hard to test. It appears maybe a group of images I was using is somehow corrupted (?) most drawn images work fine, no pictures work
Well... maybe it is EXIF after all if it's failing on photos
Cameras add metadata in the form of EXIF to photos.
ty, I learned a lot today about file formats haha
The image is stored one way but the EXIF orientation metadata tells image viewers to display it some other way
I do not think the user will plan on ever uploading pictures here. But I dont feel right ignoring it.
I am mostly surprised this is not built into django
If it's an EXIF thing then I'm not surprised.
You should find those problematic images and check if they have an orientation in the exif tag
Pillow/Django is likely just reporting how the image is actually stored rather than how it wants to be oriented
If it's not an EXIF issue then I don't know what it could be
it is probably EXIF and like a small handful of problematic images, but they are all from the same batch of downloads, so maybe there was an issue there
Hello! I'm working on a vulnerable Flask app for a training site and it's my first time going this in depth with the Framework. I have a Products page that has my fictional products and a button to find out more about the specific product. I want the button to trigger a new page as well as create a sql query on the backend to return back to a new page of /products/product
I'm stuck on how to do this
Bois i need some help with flask
Are there any hosting services that support flask
Or could I host it myself
@ or dm me if anyone knows
Thank you
yee
I need some help with my issue still as well if anyone is free
I'm planning a purposely vulnerable Flask server. The idea is for the user to go from /products and click on the Learn More buttons to go to the specific /product page for that product. That page will call the SQL server and make a vulnerable SQL query
But im having trouble figuring out the best way to creating this route from /products to /product
Currently I just have ```py
@app.route('/products', methods=['GET'])
def products():
return render_template('products.html', title='Our Products')
Which renders this
That's pretty legit
Thank you sir
Unfortunately I have no flask knowledge. I'm a django girl
maam
lmfao
I'm sure someone will come along. Yeah same. K do ur thing
figured it out
@fiery coral main isn't valid. You need to use __name__.
@quartz valley Yeah, I was following a tutorial and they messed up. Thanks.
@tawdry elbow I started typing without actually explaining my thoughts well
Ignore me
Sorry
Hey has anyone come across a nice plotly venn diagram example? For some reason there seems to only be kind of a lame static one, i was hoping for a nice dynamic web one i could put into a Dash app.
(with mouseovers of each of the sections to show number of elements etc)
@bleak bobcat Nice, ta!
Lol fixed
I'm still having some issues with my flask app. They are described abobe
Above
If anyone needs more info let me know
Maybe that's why no one has helped lol
Is it possible to make an ASGI server work on a platform that only supports WSGI? Is there some sort of adapter?
I'm building an app using FastAPI, but it's going to be hosted somewhere where ASGI isn't supported (I think)
Asgi should be supported by anything in theory
Asgi is just the async implementation over the sync version WSGI
It would fairly simple to turn as ASGI -> WSGI but not the other way round really, because the environ dictionaries and callbacks differ alot
where does django looks for a media folder in an app
because it can't find my media folder
i have specified it in the settings.py
for some reason it can find my static file but not the media folder
@manic frost Whats the host? and type?
Um, well, I haven't decided yet. My hosting, and probably other hostings in that price range use an Apache server and through some magic (with passenger) run a WSGI app.
A google search showed me this snippet https://gist.github.com/mtorromeo/f7608efc5dad47299f9e270a069c9159, and it basically runs an asgi coroutine in an event loop. Would this even work, or is it naive?
Some WSGI runners use things like PyUv to have essentially sync based event loops where they can fight each other
well, if I fail, I could use heroku, right?
Whats your budget?
something like linode or Contabo do some really cheap hosting that gives you VPS control
my budget is epsilon because it's for personal stuff for now
ah fair enouh
enough*
You can try that ASGItowsgi adapter but it might have some unintended concequences
couldnt hurt to try tho
the hosting is pretty crappy... it shadows 500 errors with non-descriptive 503 errors haha
but I was content until I started using FastAPI
how can I customize model.query return?
for example my UserModel has packages which is foreign key to PackageModel
when I query UserModel.objects.filter(whatever) I want my packages to return all except delivered packages -- (current_state != 'Delivered')
these are my models
class UserModel(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, Sequence(
'user_id_seq', start=10001, increment=1), primary_key=True)
is_admin = db.Column(db.Boolean, default=False)
is_superuser = db.Column(db.Boolean, default=False)
packages = db.relationship('PackageModel')
class PackageModel(db.Model):
__tablename__ = 'package'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey(
'user.id', ondelete='CASCADE'), nullable=False)
current_state = db.Column(
db.Enum(PackageState), nullable=False, default=PackageState.Declarations)
user = db.relationship('UserModel', back_populates='packages')
it's best practice to make that a model method
class PackageModel(db.Model):
...
@classmethod
def not_delivered_for_user(cls, user_id):
return cls.query.filter(cls.user_id == user_id, cls.current_state != 'Delivered')
and that returns a query and you can do whatever query methods you want (another filter, get the .first(), get .all() results, etc.)
hello everyone. having some trouble with flask
I have configured a 404 page
(my 500 page doesn't work and I'd also like to tackle that)
but it doesn't get triggered too often
and at this point, I intentionally want my website to trigger loads of 404 pages. how do I sensibly make that happen?
because my 404 gets triggered under very specific situations -- but not all
404, is when you enter a url that's not defined in your routes, that's when you return the 404 page
localhost:8000/lalala
lol -- creepy stuff. I literally test with /lalala lol
but how do I point flask to that? if I do localhost:8000/lalala I get 500
@app.route("/oops/")
def oops():
return not_found()
@app.errorhandler(404)
def not_found():
return render_template("not_found.html", data=today_date, page="erro"), 404 ```
I managed a workaround by defining links that are meant to route to 400 to go to /oops/, which renders the 404 page
is there any way to make /lala route to 404? I can make it with lousy if conditions, but I'd rather use a flask tool if there is one
in django, a middleware automatically redirects the user to the 404 page, not familiar with flask so can't tell you directly, but surely there must be some option to do the same
Ooooh! I just fixed it!
@app.errorhandler(404)
def not_found(e):
return render_template("not_found.html", data=today_date, page="erro"), 404 ```
this fixes it -- e as the argument for not_found
cool. thank you for the help!
im glad you fixed it 🙂
I am trying to make a decorator that return a user to a certain url when he tries to go the register page and he is logged in
def unauthenticated_user(view_func,redirect_url):
def my_func(request, *args, **kwargs):
if request.user.is_authenticated():
return redirect(redirect_url)
else:
return view_func(request, *args, **kwargs)
return my_func```
please help me
when I try to call it in my view func it tells missing one required positional argument view_func
@flint breach can you help
this is the code in my views.py :
@unauthenticated_user(redirect_url='/user/register/')
def register(request):
form = CreateUser
if request.method=="POST":
form = CreateUser(request.POST)
if form.is_valid():
user = form.save()
if user is not None:
login(request, user)
return redirect('/posts/')
else:
messages.error(request, 'Password or Username is incorrect')
return render(request, 'users/register.html', {'form':form,})
which positional arg are you missing
the view_func
that's not a positional arg, just paste the error msg
TypeError: unauthenticated_user() missing 1 required positional argument: 'view_func'
the way decorators with parameters work is like so
@decorator(arg)
def fun(args):
pass
is the same as
def fun(args):
...
decorator_to_apply = decorator(arg)
fun = decorator_to_apply(fun)
I didn't get it @dapper tusk
unauthenticated_user(redirect_url='/user/register/')
``` has to return a function that takes the view func
so you would write it like so
def unauthenticated_user(redirect_url):
def decorator(view_func):
def my_func(request, *args, **kwargs):
if request.user.is_authenticated():
return redirect(redirect_url)
else:
return view_func(request, *args, **kwargs)
return my_func
return decorator
thank you so much @dapper tusk
if i am in my app folder in Django
how to i get a function from the views.py file
example:
my view file looks like this:```python
from django.shortcuts import render, redirect, reverse
from django.http import HttpResponseRedirect
from .forms import SubscribeForm
from .models import Subscribe
def foo(i):
return i
Create your views here.
def home(request):
context = {'text': 'Thanks for Subbing'}
return render(request, 'subscribe/home.html', context)
and i want to import the foo function from another file
like you'd import a function from any other file
this file
from apscheduler.schedulers.blocking import BlockingScheduler
from .views import foo
sched = BlockingScheduler()
# Schedule job_function to be called every two hours
sched.add_job(foo, 'interval', seconds=30)
sched.start()```
yes
the file above is called send_every.py
send_every and views.py are in the same dir
but this line from .views import foo gives me this error ModuleNotFoundError: No module named '__main__.views'; '__main__' is not a package
I had this problem yesterday too @flint breach if you remember
i'm stuck here
I have tried from views import foo and from subscribe.views import foo
those don't work
Same error?
also, got an __init__ in the folder?
it has to be a package (a package has a __init__.py file) for relative imports to work
your project structure would help greatly
❯ tree
.
├── app1
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── app2
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── app3
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── demo_project
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── manage.py
7 directories, 26 files
if you want to, for example, import app2/views into app2/tests, then from .views import something should work
With Flask, I have my models.py file to be used with SQLAlchemy. Do I need to manually create the tables in the Database with the right rows or will I do that in the app?
Everything in my app is going to be predefined and set already. I'm not creating records in the DB through like a user registration. Do I need models.py at all?
sounds to me like you're describing a static site
if you have no db interaction, you don't really need it then, no
I do
There is DB interaction
I'm querying it to return fields from it
But I'm not making entries into it at all
Only 4 things for products
if the answer is never, and little, a db seems overkill to say the least
Maybe so but it has a purpose here
I'm designing it to be intentionally vulnerable to SQLi
sqlite?
wew, seems very overkill
sqlalchemy sounds overkill, a full blown orm
but then again, so does mysql, so 🤷♂️
So how can I do this
Just cuz it's overkill doesn't mean it isn't possible
I just need some help
Would Flask-MySql be better suited?
Then I don't think Id need SQLAlchemy
And models.py
don't get me wrong, of course it's possible, im just not familiar with flask, so im waiting for someone else to give better advice 😛
I am making a web app using flask. in my app.py file, I am trying to import modules from a custom module file that is in the same directory. my editor (vscode) is saying "unresolved import".
make sure you are in the same working directory, that was my issue when I was trying to use custom modules
claim a help channel and ill see if I can help you fix it :D
can someone tell me why does postgres have 2 id columns? using flask sqlalachemy? the first ID column works normally but the 2nd id columns increments and stays even after one is deleted.
example:
user one = ID #1
I deleted user one.
i create user one again = ID #2
Sqlalchemy probably automatically create a primary key as an auto increment id
The IDs are not reused because they are often used as unique identifiers
ahh, that makes sense! thank you!
Does anyone know of any professional websites that are coded with Python Django?
instagram & pinterest
Are they coded fully in Python Django?
I'm sure there are some aspects that are outside django, such as the frontend and mobile apps, product analytics, etc.
but yes, they use django- also check this site out https://www.djangosites.org/
The most comprehensive listing of websites that are powered by Django, the python web framework for perfectionists with deadlines.
If I have images in a random directory on a remote server, can Flask somehow connect to it and display the images on the frontend (Flask would be running on a separate server)
Can this be done without using a database
If I'm adding all of the entries to my tables through the MySQL shell and only need to perform queries on the database (SELECT only), do I need an ORM?
Can I just use Flask-MySql
I'd go with SQLAlchemy
Full disclosure my tables aren't going to ever be modified by the app or be added to. They're just there to be queried
I need the app to be able to make raw SQL queries too. I haven't seen how to do that with SQLAlchemy
I already have my models and all with SQLAlchemy but I just don't know how to configure it for MySQL. I only ever see sqlite tutorials
And guides
What do you think? @cold socket
@tawdry elbow Do you mean something like rs = con.execute('SELECT * FROM table;')
Mhm
@tawdry elbow Maybe check this out http://zetcode.com/db/sqlalchemy/rawsql/
In this part of the SQLAlchemy tutorial, work with raw SQL.
That helps a bit
With REST endpoints, what is the best practice for this scenario?
I want the client to initiate the creation of an object on the server, but the client isn't specifying any details about the object being created; that is all being handled by the server.
Is it ok to POST to /my_objects/ with no data, or is there a more preferred way?
Hi, I have a important question. How can i deploy flask app to apache? Is it possible to run apache on raspberry pi (zero)? I haven't find helpful tutorials so I am asking here
Guys is it possible to deploy a flask application to an apache server? If yes , how?
And mention me if you want to answer please
why cant django find my media filelelele can someone please double check im doing this media file things right
bois i have a question about gunicorn
how do i make it run outside of localhost?
pls @ or dm me if you have an answer
Anyone knows why is uvicorn called uvicorn?
@left jungle flask and apache are very different, generally you don't mix gjr two
Anyone know how to save datas from website directly to database....i also have a submit button after i click in it i wanna save those data to the database....i have a webserver python and a post method in <form> too and i wanna save those datas in website in database after i started my webserver and click on submit
@left jungle I host my Django with apache. I am sure Flask would work as well, but I do not use flask.
Yes, you should be able to run flask on Raspbian (I think they renamed it)
@wanton ridge are you using a framework? With Django this would be handled most likely through an API call or simply through the view by running the .save() method on your form
somebody know ho to write a proxy for nike login ?
it's best practice to make that a model method
@cold anchor I know, but, there is a reason.
right now, I really need to make PackageModel return that way. how do I change model return default?
anyone familiar with http server?
Nah, nobody is. What's the question ?
get data directly to database with http server
What's the action on your form ?
if anyone can help me with a bot I'm making to pull jpegs off a website and tweet them, i would appreciate it very much...I started this project in JS, but I think I should probably be using python.
I have a twitter dev account made already and have it set up to be able to tweet stuff...but I might as well be doing it manually if I can automate the image scraping to use to tweet
Well that's not how it works...The action needs to be a url
i also try it
but after click on button datas wont be send directly to database
i also connect my python to mariadb
Because you need to process it and send it to the database yourself, it's not magic
your code writes a hard-coded commit to the database, you need to write a way to parse your data that is passed to do_POST()
cant u just click on submit and those datas will be send directly to database?
let me send code
no
No
you can send your data to your SERVER, the database needs to know what it means
This is similar to:
If you throw peanuts and grapes at a loaf of bread, it does not make a peanut butter and jelly sandwich.
You first need to make peanut butter from the peanuts, jelly from the grapes. You STILL dont have a sandwich, so now you need to assemble everything
and my values are %s and after it succes record i search the SELECT * form antworten11 i get those %s
This is similar to:
If you throw peanuts and grapes at a loaf of bread, it does not make a peanut butter and jelly sandwich.
You first need to make peanut butter from the peanuts, jelly from the grapes. You STILL dont have a sandwich, so now you need to assemble everything
@acoustic oyster lol yh
You get data from the form => data goes to JS => data goes to python => you then clean and parse the data => you send the data to SQL with a query
yep after click submit i can go to inspector and see those datas as json which i made in js
but then i have to type those manually in insert into antworten11 VALUES... myself but i dont want to type it manually
I want to redirect to login page after logging out from the administration page too. How can I do that? (django 3.x)
can somebody please show me how to code a nike login..
hello
What is the best database to use for implementing a login system on a website?
https://hastebin.com/vomibupoho.py Can anyone help me and tell me if I'm making the connection and performing the SQL the right way? I know you aren't supposed to make a new connection per request so I'd want to do it the right way. Does anybody have any tips?
I need to use raw SQL so that's not my issue
Sup beautiful people, i was trying to connect mysql to django but apparently while installing mysqlclient it shows an error.
It says the wheel is not supported on this platform
I was trying to do it on windows before, havent tried it on linux.
https://hastebin.com/vomibupoho.py Can anyone help me and tell me if I'm making the connection and performing the SQL the right way? I know you aren't supposed to make a new connection per request so I'd want to do it the right way. Does anybody have any tips?
@tawdry elbow You're not supposed to use f-string or any kind of string concatenation while passing user input values.
Db libraries provide parameterization for Db queries, like so:
cur.execute("select * from table where col = %s", ("value",))
Okay good I'm glad you caught that
It's done on purpose
Any other suggestions on changing how the database is connected to? I would think I'd want to open a connection upon the app being loaded (i.e. the main index being requested) and then pass that connection around to my other routes to make queries on...or rather, just the one lol
How would I do that?
real talk
why does related_name='+' in django exist
just an annoyance that the reverse relationship is not available
Me too
content = post [1] + ': ' + post[2]```
should display things in a list like this
```name: content
name1: content1```
but it displays this instead
[(message id, 'name', 'content')]
if anyone has any ideas
pls @ me
how is this relevant to webdev?
how do u set a background image on flask?
You mean in CSS?
how is this relevant to webdev?
@flint breach because its getting the input/input variable from flask and outputting it to another flask site
fair, but the specific code section that's bothering you has nothing to do with webdev, more of a general py question
can you show the posts variable
How do you display the content?
can you show the posts variable
@flint breach
posts is
posts = get_posts()
and thats a function from another python file i imported
con = sql.connect(path.join(root, 'database.db'))
cur = con.cursor()
cur.execute('select * from posts')
posts = cur.fetchall()
return posts```
anyone know which SQL engine has the least issues with Django? Tried installing MySQL and it just gives a bunch of wheels issues, even tried downloading the mirror someone suggested on Stack Overflow and still the same issue, smh.
Sqlite is the simplest
sqlite for a production app though?
nah, i'd recommend postgres
ok
mysql or mariadb shouldn't be problematic either afaik
any specific version of postgres
meh, anything that's not bleeding edge (the latest version) or an old ass version should be fine
ii
Can anyone help me with my question? I'm trying to figure out the best way to create my connection to my database so it doesn't break anything or cause unnecessary lpad
I'm not sure what I'm doing currently is correct
Can anyone help me with my question? I'm trying to figure out the best way to create my connection to my database so it doesn't break anything or cause unnecessary lpad
@tawdry elbow what kind?
i mean whatre you using to connect to it (sqlite, postgres, etc)
@flint breach
posts is
posts = get_posts()
and thats a function from another python file i importedcon = sql.connect(path.join(root, 'database.db')) cur = con.cursor() cur.execute('select * from posts') posts = cur.fetchall() return posts```
@balmy shard print(posts) for me
@balmy shard print(posts) for me
@flint breach[(330, 'Cylinder', 'test')]
and you want the list to be ['Cylinder: test'] or what?
https://hastebin.com/vomibupoho.py MYSQL using SQLAlchemy
id like it to be
Other_name: test
where do you get other_name from
i just made up the other one
you just want to print it or have a new list from it?
or, modify the existing list?
Hi, for DRF, is it okay if I only have JWT Authentication under DEFAULT_AUTHENTICATION_CLASSES or will I not work with sessions?
The problem I'm facing right now with sessions enabled is whenever the server restarts, it deletes all sessions and it doesn't seem to check if there's an existing JWT token so it just throws an Unauthorized error.
perhaps a dict
ok
new_posts = {key: value for _, key, value in posts}```
that's one option, given that you don't really know what you want with it 😛
one tip, think what you wanna do with it, before you start coding
otherwise you'll just stumble over yourself
i don't think you gained much by having it in a dictionary, unless you need constant lookup time
but im gueesing you don't really?
fair
i don't think you gained much by having it in a dictionary, unless you need constant lookup time
@flint breach i made a thing to send it to a mailtrap inbox so i can keep it without looking at the database or turning on the site
What are th differences between one database and another
Acid
coffee
guys where can i learn to set up a web server after learning to develop a website through flask?
Hello all. I hope you have a great day. I feel confident with the basics of Python and now I want to start my journey with web development. Any recommendations from where to start?
yeah i'd say from this tutorial with flask https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
@app.route('/logout', methods=['GET'])
@client.is_logged_in
def logout():
client.logout()
return redirect(url_for('index'))
I have a route like this, and I provide a redirect too. Still it returns an error
Traceback (most recent call last):
File "C:\Users\kanna\.virtualenvs\OpenCity-Dashboard-9CrIeGsV\lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\kanna\.virtualenvs\OpenCity-Dashboard-9CrIeGsV\lib\site-packages\flask\app.py", line 1953, in full_dispatch_request
return self.finalize_request(rv)
File "C:\Users\kanna\.virtualenvs\OpenCity-Dashboard-9CrIeGsV\lib\site-packages\flask\app.py", line 1968, in finalize_request
response = self.make_response(rv)
File "C:\Users\kanna\.virtualenvs\OpenCity-Dashboard-9CrIeGsV\lib\site-packages\flask\app.py", line 2097, in make_response
raise TypeError(
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.
@cloud path thank you
how worth it is it to learn django? im just getting into it and it seems like it handles sessions & saving them to the db which is awesome
django probably worth learning, but as a beginner i chose flask and id say i made the good choice
i watched some django tutorials and it seems easier cuz the concepts feel the same to me
Has anyone here worked with flask? I'm having trouble getting AJAX to successfully send a JSON to my flask script.
Sure. Can you post an example of both the js and the flask
Sure thing!
I think that's the link. I put them both on the same document here, but they are in seperate files obviously haha.
That's just the flask route for the specific page. If you need the rest of the flask, let me know!
I don't remember the Jquery side of things well enough to say exactly what's going wrong - but I'm pretty sure the problem is on that side of things
That's what I figured. I'm terrible with JS and Jquery haha
I'm assuming this never triggers? print(test)
Correct, it times out with get.
For some reason it's sending testVariable as a nonetype
document.getElementById('submit_button').addEventListener('click', function () {
var testVariable = "hello, this is a test";
$.post( "/", { name: "John", time: "2pm" } );
})
try replacing you js with that
json.stringify is converting a javascript object into json format
but you want to be sending it a object I think
Still considered nonetype