#web-development
2 messages ยท Page 212 of 1
Hi all. I built a flask app that gives me dog images via an API it requests pictures from.
Im wondering how to make a panel and a button for a page. I imagine being able to give users the ability to click the button and getting a new image in the panel until they decide to quit.
Whatโs the best way to go about this?
How can you process an image and then upload it to a Django ImageField within the model?
This doesn't explain the processing part though?
At least for me, there is an attribute error whenever I try to process an image file
Django Image Field stores just path to image
the image is stored at your local path in filesystem
so the procedure would be...
Store image in Image Field
get its path
run processing commands on it
Optionally, saving to DB only at this point the path
The biggest trouble I see with images in general...
that only their path is stored in db
while it should be ideally stored the image itself ๐
fixing it, you need to do something like....
converting image to base64
and storing base64 in db
usually MongoDB is recommended for file/image storaging though
not sure how well SQL database will work with it
it depends on, can it store images with floating size? should be good without contraint in theory, it needs to be checked
class TiffModel(models.Model):
name = models.CharField(max_length=450)
image = models.ImageField(blank = True, null = True)
processed_image = models.ImageField(blank = True, null = True)
def save(self):
img = Image.open(self.image)
output = BytesIO()
images = []
tensors = []
processedArrays = []
tiffStack = []
###=============== Conversion ================###
# Read tif, convert each page into arrays in images[]
for i in range(img.n_frames):
img.seek(i)
images.append(np.asarray(img))
# Read every numpy array, convert to tensorflow, process by dividing by 2
for x in images:
tensorX = tf.convert_to_tensor(x)
processedTensor = tf.math.divide(tensorX,2)
tensors.append(processedTensor)
# Convert back to numpy array
for x in tensors:
processedArrays.append(x.numpy())
# Convert to tif
for x in processedArrays:
tiffStack.append(Image.fromarray(x))
img = tiffStack[0].save(self.name + ".tiff", compression="tiff_deflate", save_all=True, append_images=tiffStack[1:])
# Save tiff file into model data
img.save(output, format = 'TIFF', quality=100)
output.seek(0)
self.processed_image = InMemoryUploadedFile(output, 'ImageField', "%s.tiff" %self.img.name.split('.')[0], 'image/tiff', sys.getsizeof(output), None)
super(TiffModel, self).self()
I think the processing part worked well enough, but the actual saving to model throws an error everytime
Would you say the base64 approach would be effective to solve this issue?
according to a bit of googling
base64 approach is not advised
they recommend continue storing just file paths
due to higher speed efficiency
But, that's not final answer, because NoSQL databases potentially can be good
some people who dealt with them should be asked
The discussion for deciding the best way for storing images in Blob vs FileSystem is a never ending discussion. Iโm creating this blog toโฆ
10 votes and 8 comments so far on Reddit
every discussion advises to follow the django ImageField path. storing image in filesystem and storing only metadata in database
there are some cases when it could be cool to store it completely in dbs, but highly likely it is not yours
I want to achieve this.. Which will be optimal way to do multiple forms? Also multiple files, email sending (have done already not difficult for me outside django, but does not have an idea to achieve in django in my context), pdf template for downloading report.. I am Django Beginner.. Kindly share some resources (short videos, or blogs) , ideas to do it easily (expert opionion), github repos (each part perfectly explained separately or combined).. Thanks alot in advance..
it sounds like a mix of heavy frontend with a bit of backend
you should look into getting a hang of one of big three frontend frameworks: React / Angular / Vue.js
backend framework will add just login feature + ability to send by email
most of the heavy coding would be needed in frontend
I could recommend this book to get started in frontend basics ๐
And this one for javascript
After those two, getting started in Vue.js or React should be not a problem
depending on how you value your data safety about user logins and scaling, backend could be potentially a lot of work to do too, but that would be technically non essential for minimum viable product ;b
Ohh I see I though it is totally backend work.. I have done some work already but not satisfied with my results so asking here... I know html css, a bit.. But you shocked me that it is heavy frontend task.. But how can I manage multiple forms in context of django? by the way thanks for answering..
you wrote in your specs ability for correct data. That can be made in backend too, but frontend will make it instanteous without requests to server and better? although better to validate data at frontend and backend at the same time.
but mostly, you wished to add multiple files... which if u wish to make a nice interface for adding them, requires again frontend
Technically, you can do all of it purely in backend framework
where you need you can apply just a regular Javascript / JQuery, but you know... it will be a pain in the ass ๐
you will have far less capabilities to implement nice visual interactive interface
frontend framework will give freedom to implement all desired features at maximum
yes.. I was thinking here backend before but you guided me to frontend.. Although I think you guide me easy way (what I think).. A little bit of backend (no need of file validation except for file format which is not that hard)..
login is easy and done already in django.. the only issue was multiple forms and files.. which is I think easy in JS.. let me search for it on web...
Thanks you guided me well.. Thanks..
u a welcome. although remember that even if login is easy and works out of the box.
you are restricted in those defaults to have just one working database without mechanisms to restore data in case of data loses
fine for minimum viable product, but a food for thoughts to think for scaling/data safety situations if necessary
yes.. django is easy in login and database sense.. just multiple forms is big deal in django..
technically you could do it all with django ๐ค
just page one: your first form
sending result to verification into backend and send back as sticky cookie
rendering form 2
inputting email and sending back to django
reading the cookie with data from form 1
doing stuff, sending answer
the only a bit I am unsure, how multiple files attaching works ๐ never needed it
bare bones functilnality but still a functionality
files in media can be retrieved..and then send as attachment..
yes, nice introduction to javascript
and have a shame to be not distributing pirate copies here
@inland oak do they make some book like a brain friendly guide head first brainf or head first asm?
i want to learn asm....
yes.. he should share publisher's site.. it is pirated file..
asm as in assembly language?
yes
https://www.amazon.com/Head-First-Series-Books/b?ie=UTF8&node=8456760011
no, the closest they have to low level programming is C book as far as i know
Online shopping for Head First Series from a great selection at Books Store.
hmm... it means asm is not brain friendly lol ok
https://www.amazon.com/Head-First-Series-Books/b?ie=UTF8&node=8456760011 whole list of head first books
Online shopping for Head First Series from a great selection at Books Store.
some of them became a bit outdated
Tysm I love you โค๏ธ
Oh er https://www.geeksforgeeks.org/overriding-the-save-method-django-models/ was really helpful
Hi all,
I should do following task by python as a rehearsal:
"Create a load-balanced (public) REST API serving some json from an existing (loaded)
database and make it trivially easy to deploy on either AWS"
I don't know what does "load-balanced (public) REST API" mean!!? I would appreciate it if anyone could help me for understand it.
usually people assume having API served at several machines (with assuming they have separate physical resources).
API served at machines should be exact replica/copy of each other.
which are having attached to them Cloud Provider Load Balancer object
Load Balancer will be standing on front of them, and distributing traffic between several machines
so Load Blaancer would be having its own Public IP
user requests your backend at loadbalancer public IP
and he is redirected semi-randomly to one of your replicated APIs
thus distributing workload on machines horizontaly
the task can be fulfilled in actually at least three ways
- Most simple way:
manually installing REST API at every server
and raising load balancer as another VPS that has HAPROXY installed with config pointing to your REST APIs
(Or optionally manually clicking cloud provider GUI to have cloud providers Load Balancer)
- Smarter way:
You use at Least Docker to install applications
- Even smarter way:
You use Ansible to auto install REST API and Haproxy load balancer as code from your development machine
- Even smarter way further:
You scratch the haproxy VPS and instead
you write terraform code (or Pulumi or similar tool used), that raises cloud provider load balancer pointed to your VPSes with REST APIs
- Even smarter way beyond further:
You don't deploy your code on your own, CI tool like Gitlab CI tool does it for you, you just press a button to confirm production deployment if necessary, or no buttons is pressed, just code git commited to repository ๐
- Ultimate way:
Your terraform code creates Kubernetes Cluster
REST API is auto loaded to docker registry by Gitlab CI
Gitlab CI applies manifests to auto install everything into cluster
Kubernetes auto creates providers cloud balancer
Thank you very much for your absolute explanation. ๐ I'm familiar with terraform, ansible, docker, ... and totally designing CICD but in this case I don't know how should I create REST API by python
so, you know tools just without kubernetes?
No I know k8s as well
well, then use Ultimate way. ๐
All you need making dockerized python web application that gives at least hello world
10 code lines to do that + docker file
and dose it contain "... serving some json from an existing (loaded)
database" ?
from flask import Flask
from flask import jsonify
app = Flask(__name__)
@app.route("/")
def hello_world():
return jsonify("message": "Hello, World!")
it certainly contains serving some json
REST API is not assuming database usage
although wait
perhaps assumes ๐ค
or not
no, no. mistook it with CRUDe applications.
https://www.redhat.com/en/topics/api/what-is-a-rest-api#:~:text=A REST API (also%20known,by%20computer%20scientist%20Roy%20Fielding.
It looks like REST API assumes just having stateless JSON formatted application
So you should be good without database
Thank you so much for your help, ๐ so I should start
should be easy as pie for you. if you already know all the infrastructure tools ๐
just make sure to serve your python application with gunicorn or something like that inside the container
and not with dev server
for sure thanks
I'm using django, how do I specify the path from where to get the templates? It takes by default from Personal Account\templates\ and I need from Main\templates\ Help pleas
can you share template config from settings.py
?
Hi.. I want some html table editable with styles.. Which can communicate easily data with django... How? resources needed...
Hello everyone I'm new here! Name's Mike๐โโ๏ธ
Not really ๐ค
Even with crud you don't have to store data, at least yourself ๐
Also i guess you can fire some kind of events via crud api? e.g. sending a push notification
i mean, I thought CRUD is basically basic operations with database
creating / reading / updating / deleting those objects
it is a bit hard to imagine how can be CRUD without some stateful objects lifecycle to change
Yeah, but you don't have to store them yourself, your CRUD api could be a gateway to some microservice
๐ค more proxies to the god of proxies.
Yep
(django) is there any built in non negative validator for duration field?
For python web developers, didn't you need to understand networking?
For People who did what did you learn.
good day everyone, please I want to know why this isn't displaying what's on my view. This is django by the way
Hey @crisp cove!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
you probably have improperly configured urls or raising Http404 inside your view
Thanks I've figured it out
so what was the problem?
I solved this problem/ Thanks
Rather, you forgot to add a link to the urls.
Django project: I have a CBV to display information about a Volunteer object. In that view, I'd like to display a list of objects (VolunteeringJob) related to the Volunteer object. Each line in that related objects list will have a delete button. So I was wondering what's the best way to handle this?
My initial idea was to have a seperate view for VolunteeringJob and my information view would call its get to have the list, then call its delete to delete an entry and so on. Is there a better way/different way to do it?
can someone help me with react + django?
i'm making a job portal
want to do stripe intigration
React is a frontend framework
i know that
And stripe is something you would do on the backend
yes
Hey everyone
In this video, we'll implement Stripe Payments and Stripe Checkout with Django.
๐ Read the blog post
https://justdjango.com/blog/django-stripe-payments-tutorial
๐ป Project code
https://github.com/justdjango/django-stripe-tutorial
Build a Gumroad clone with Django:
๐ https://learn.justdjango.com
โ๏ธ Stay in touch
Facebook: htt...
Oh lmao
i need some other logic
you can search something up on google
yes
like โstripe integration with Djangoโ
I canโt really help as I have never used stripe and have minimal react experience
But I do have some Django experience
Can i ping DM?
Sure
Can you ping me? i'm not able to ping you
Try now
in python, I have the following code:
views.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('wall/', include('art.urls')),
path('admin/', admin.site.urls),
]
and when I go onto there, it returns a PageNotFound. All the code is in wall/, but how would I redirect the user to wall/ once they enter my development server? 
im guessing this is your urls.py rather?
you can use django's redirect view for / the home page to redirect to /wall/
here is the documentation
lemme know if you face any problems regarding the redirect
this is be all you need
path('/', RedirectView.as_view(url='/wall'), name='go-to-wall'),
you can also give the pattern name instead of url
which is better flask or django?
oh, yeah
.bm
ok
is the bot responding
thanks btw
!warn @regal root Stop spamming. This is not a platform for hiring or job seeking.
:incoming_envelope: :ok_hand: applied warning to @regal root.
Sorry
Hey! Has anyone done Angela yu web development course??
Hey, can someone help me find a themeforest HTML template for the following. I am trying to find a site that allows students to submit online projects under different categories. This is in case something similar to the science fair gets cancelled, there will be a backup way for judges to view and judge the projects. Basicly, I want something as close to that. If you are able to help please dm me with the link of the site you found. Thank you!
Hello can someone help me in my flask project
i have a admin dashboard
in which students can post their complaints on the panel and on the home page of the panel all the complaints which student has posted will be shown there
and here i have two student for example
the main problem is .. when I post a complaint from first student account, then all the complaints are visible on the second student's home page also
i want complaints on home page of the user who is currently logged in
this is the problem
In simple terms - A student can see only their posts(or complaints) on their admin panel rather than seeing every student's posts
:incoming_envelope: :ok_hand: applied mute to @tribal tusk until <t:1642439046:f> (9 minutes and 59 seconds) (reason: mentions rule: sent 16 mentions in 10s).
!ban 927832768078020608 Only here to disrupt voice channel and spam ping.
:incoming_envelope: :ok_hand: applied ban to @tribal tusk permanently.
i don't think your issue is to do with flask itself. are you maintaining a mapping of userid-complaintid when you store the complaints? i.e. do you have a studentid column for the table where you store the complaints? you need to know which user posted which complaint in order to be able to filter that, right?
Hi, does anyone know flask and flask-sqlalchemy?
I have problem with proejct structure and database relations
I'm sure there are quite a few users that used both here
Do I need database.py file?
also where should I include this db = SQLAlchemy(app) into app or models file?
I'm a bit rusty on flask web dev, but I'd say you'd put that into app file, if you're not thinking yet about directory structure
if you only have models.py file, I would not create database.py atm
and in app.py Im including modules.py by from modules import * right?
hmm. as a general rule, I think you want to avoid wildcard ('*') imports
ok, so just classes with tabels I guess
try to follow the documentation. that'd be my recommendation
I was recently asked about what's the best way to import stuff in python and I could give a straight answer. copied from pep8:
import mypkg.sibling
from mypkg import sibling
from mypkg.sibling import example
as far as I understand pep8 gives no preference to:
import mypkg.sibling
from mypkg import sibling
but which is better?
what makes less mess in your imports ;b
while remaining precise what u use
prefering precise imports, using mass import as package to avoid too many imports
although import as package has advantage
over precise import
(np)
because anywhere in your code, it is seen from which package the function is
so... I guess package import is good as general method
If someone has any good flask-sqlalchemy repo with modules, cofig and database relations repo I would liek to see
Darkwind, tnx
this may be outdated somewhat
but in general look to miguel for guidance
not certain, but I think he's also the author of the flask sqlalchemy extension
(altough, I may have read some critiques about it from sqlalchemy devs sometime ago)
@feral night ignore the link above
oh ok haha
sorry
my mistake
don't
I've seen this post: https://blog.miguelgrinberg.com/post/flask-mega-tutorial-update-flask-2-0-and-more
I'm excited to share that I've completed a revision of the Flask Mega-Tutorial to keep it in line with new releases of Flask, Python and third-party dependencies.To celebrate this update, you canโฆ
I just need a good guide how to connacthe files like: app.py, modules.py, this for sure: config.yml and routes,py
but it links to the post above
I just thought the post above was outdated, because it's dated to 2017
but it seem it's up to date
also from the first link thats dated to 2017:
there's metadata on the site like:
$ python3
Python 3.9.6 (default, Jul 10 2021, 16:13:29)
so it's been updated for sure
my web development road started literally from this tutorial ;b
I was complete zero, and was given to implement everything from the guide within 5 days
so should I follow this tutorial or do Yo urecommend something diffrent?
this is good tutorial ๐
ok thanks
I was hired because of it
๐
someone should mention to Miguel to update the date on the tutorial post
Do I need to import db here in routes.py?
from flask import jsonify, request
@app.route("/")
def hello_world():
message = {
'message':'Connected!'
}
resp = jsonify(message)
return resp
@app.route('/api/add-data', methods=['GET', 'POST'])
def submit():
if request.method == 'POST':
if request.is_json:
data = request.get_json()
new_label = label(label_name=data['label_name'])
new_question = questions(question=data['question'])
new_answers = answers(answers=data['answers'])
db.session.add_all([new_label,new_question,new_answers])
db.session.commit()
return {"message": f"Data has been sent successfully."}
else:
return {"error": "The request payload is not in JSON format"}
# Get All Data
@app.route('/api/get-data', methods=['GET'])
def get_all():
if request.method == 'GET':
all_labels = label.query.all()
all_questions = questions.query.all()
all_answers = answers.query.all()
return jsonify(all_labels+all_answers+all_questions)```
and tables?
Hello guys !! Please can someone tell me what best language for backend ?
@native tide @verbal pagoda Thanks guys
You can use JavaScript, c#, Python, rust, etc
Thanks !! What your preference and why ?
I honestly love c# and asp.net core
C# and the .net platform is growing in popularity and will definitely be useful In the future
Itโs also really fun to work with
Great !!
Actually I was thinking to go with node.js or django .
those are great options
Definitely I will try node because I have strong background in JavaScript
lol
what are we lol-ing
just that django is python?
I guess it is a strange requirement to have 1 year of python and 2 of django
If you have two years of Django, you have two years of Python. Not a big deal, just a little silly.
yeah I see what you mean
I will say that it is very different to be scripting with python and writing a website with django
True. But if you have 2 years of experience with Django, doing scripting with Python should be no problem.
Finding someone that has done 2 years of Django without having done python scripting first in some capacity is like finding a unicorn. If you did find someone with only 2 years of writing Django code, I bet they would struggle to script things in Python.
It's much more likely that they started with Python scripting and then picked up Django so pretty hard to test the theory
yeah I wonder. It seems like people try to jump into web development with django without having much programming experience beforehand though
at least from things I've seen in this channel
I feel like I've seen quite a few people just diving in the deep end
for sure
I feel like being good at django isn't about knowing python, it's about knowing all the class based views you can inherit from, how to write better sql queries through the orm, popular 3rd party django plugins like DRF and django-filter...
I've done a lot of Django the past couple of years, but still get to write regular python too which is nice.
incidentally, it makes you a better architect in the end IMO
I learned Python through learning Django which I learned through TDD with Obey the testing goat. I've got bruised quite a bit and wouldn't recommend it that much, but I learned a ton. I've never learned Python scripting before that at all.
I stand corrected. So was basic python scripting difficult when you tried it or do you think Django filled in a lot of that info?
Learning and doing Django really taught me a lot of the Python basics: inheritance, list comprehension, using packages, testing, etc. I mean, at some point in a project you'll have to extend Django code using Python basics and advanced stuff. In my case it was very formative and I learned a ton on the side (reading two scoops, TDD, CI/CD, Docker, Ansible, Terraform, Git, GitLab products, Django-cookiecutter, SAST, databases, reading and understanding documentation, payment integration, etc.)
I have to say that before that I had done C++, Java and C#, so I had some good bases on programming.
thanks for sharing, giant.
How can I get all data witch relations?
@app.route('/api/get-data', methods=['GET'])
def get_all():
if request.method == 'GET':
all_labels = Label.query()
all_questions = Questions.query()
all_answers = Answers.query()
result1 = labels_schema.dump(all_labels)
result2 = questions_schema.dump(all_questions)
result3 = answers_schema.dump(all_answers)
return jsonify(result1+result2+result3)
Yeah, you pretty much made my point. If you're learning Django, it means you're probably trying to do something that can't be achieved with Wix, Wordpress, Shopify, etc..., and you'll have to write some custom code, which means you will probably be writing Python.
? can you explain further
i do not understand
from app import db,ma
class Label(db.Model):
"""Data model for Labels."""
__tablename__ = 'Label'
label_id = db.Column(
db.Integer,
primary_key=True,
)
label_name = db.Column(
db.String(64)
)
# Label Schema
class LabelSchema(ma.Schema):
class Meta:
fields=('label_id','label_name')
# Init Schema
label_schema = LabelSchema()
labels_schema = LabelSchema(many=True)
class Questions(db.Model):
"""Data model for Questions."""
__tablename__ = 'Questions'
question_id = db.Column(
db.Integer,
primary_key=True,
autoincrement=True
)
question = db.Column(
db.String(64),
index=False,
unique=True,
nullable=False
)
label_id = db.Column(
db.Integer,
db.ForeignKey('Label.label_id')
)
label = db.relationship('Label',lazy='select', backref=db.backref('Question', lazy='joined'))
# Question Schema
class QuestionSchema(ma.Schema):
class Meta:
fields=('question_id','question')
# Init Schema
question_schema = QuestionSchema()
questions_schema = QuestionSchema(many=True)
class Answers(db.Model):
"""Data model for Answers."""
__tablename__ = 'Answers'
answer_id = db.Column(
db.Integer,
primary_key=True,
autoincrement=True
)
answers = db.Column(
db.String(64),
index=False,
unique=True,
nullable=False
)
question_id = db.Column(
db.Integer,
db.ForeignKey('Questions.question_id')
)
question = db.relationship('Questions',lazy='select', backref=db.backref('Answers', lazy='joined'))
# Answers Schema
class AnswersSchema(ma.Schema):
class Meta:
fields=('answers_id', 'answers')
# Init Schema
answer_schema = AnswersSchema()
answers_schema = AnswersSchema(many=True)
Look at PK and FK
I want to query everyting with relations
like
Label_name, question, answers
connected by relations
I'm in the middle of finding a solution
@app.route('/api/get-data', methods=['GET'])
def get_all():
if request.method == 'GET':
# all_labels = Label.query.join(Label.label_name.filter(Questions.question))
#all_questions = Questions.query.filter(Questions.label_id).join(Label.label_id==Questions.label_id).all()
# all_answers = Answers.query.all()
all_questions = db.session.query(Questions,Label).select_from(Questions).join(Label).all()
# result1 = labels_schema.dump(all_labels)
result2 = questions_schema.dump(all_questions)
# result3 = answers_schema.dump(all_answers)
return jsonify(result2)```
still that's not it
any ideas please?
@native tide
oh ok, thanks
what is "db"
A year and few months ago my mad marathon began.
Worked at least 8 hours and more in working days
Plus often spending evenings and weekends time to self studies.
Anything I learned I applied at work and had a lot of practice to solidify every skill
My start was exactly after finishing university
did you make sure to add django_cors_headers to your installed apps and middleware too?
'django.middleware.security.SecurityMiddleware',
"corsheaders.middleware.CorsMiddleware",
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]```
Requirement already satisfied: django-cors-headers in ./env/lib/python3.6/site-packages (3.10.1)
Requirement already satisfied: Django>=2.2 in ./env/lib/python3.6/site-packages (from django-cors-headers) (3.2.10)
Requirement already satisfied: pytz in ./env/lib/python3.6/site-packages (from Django>=2.2->django-cors-headers) (2021.3)
Requirement already satisfied: sqlparse>=0.2.2 in ./env/lib/python3.6/site-packages (from Django>=2.2->django-cors-headers) (0.4.2)
Requirement already satisfied: asgiref<4,>=3.3.2 in ./env/lib/python3.6/site-packages (from Django>=2.2->django-cors-headers) (3.4.1)
Requirement already satisfied: typing-extensions in ./env/lib/python3.6/site-packages (from asgiref<4,>=3.3.2->Django>=2.2->django-cors-headers) (4.0.1)```
Can you please check?
How do I write tests for websites?
Can someone please explain what does the scope attribute do i have a hard time understanding it. Thanks!
there are a variety of libraries you can use to create testing with, like selenium, jest, and many others that are worth learning
hey guys, what would websockets be used for in a CRUD application
yeah thats a good how could you write comerical tests for a django crud application, selenium sounds good but how would that tie in terms of CI/CD
popular web sockets application: Live Chats, for example Live Chat Support
hey guys does anyone know how i can transfer AWS route 53 registered domain to cloudflare
because when i try to point the nameservers towards cloudflare, it never detects it
thanks ๐
are these libraries compatible?
- djangorestframework
- django-cors-headers
- celery
- django-redis
- django-celery-beat
- django-celery-results
- django-graphql-jwt
``` no matter if I don't know their functionality
Hi Guys
I am Bash
i made a project using computer visoin and AI
This is the link, can you guys reiview it and give me suggestions ?
they should be. I dealt with everything except graphql
there only possible trouble I can see in
- djangorestframework
- django-cors-headers
- django-graphql-jwt
they all deal with modifying a bit requests (if to look just at names from afar), so in theory there can be some sort of trouble, so better to check ๐
ah okay
hey mate
can you help me make a descion
is graphql better than rest?
apparently they can work side by side
but in a application that uses both, what kind of application would that be
apply REST for simple stuff
apply graphql when you have complex input/output requests
oohh
i did not deal with graphql, but that's my presumption.
thats very helpful
i dont think i would have many complex data commuinications
im gonna add in some statistics later on the application, but i wont have large quantity of data
as far as I know graphql allows to make better granularity to requests.
in one request you can query data with multiple relationship between.... lets say model objects
and to receive output matching those requests in one go
so it could be efficient for stuff like quering data of Social Network profile type
I guess. We can get all data in one request instead of multiple ones
the proffit in faster request time there is indeed
that's just my assumption about how graphql works, I stil did not deal with it ๐
i was more spending time to learn how to do better infrastructure and faster development
still having a lot to learn
lol, better infrastructure in Django xD
btw do you have any idea about redis/kafka/pubsec ?
a person told me i need a cache
I use redis to implement Message Queue pattern through Celery in order to distribute workload of a heavy task horizonally into many servers
oh wow, im also using celery
I am interested to learn kafka next. It would make a nice architecture
as far as I know Kafka implements Event Streaming pattern, where we can send send events into it and attaching multiple backend listeners to the events
the difference is that perhaps it is possible to have multiple subscribers to one published event, probably
and that kafka stores those events in some different way probably
and just in general listeners are attached in a bit different way to distribute workload
.... basically my knowledge about kafka ends at 5 years old knowledge
wait a second
I need to implement 2 timers for both chess players, this could be done with just setInterval and decrement the timer every second but it isn't accurate and tend to drift so we could instead calculate the timedelta from a datetime to the future called <white/black>EndDatetime and subtract current time from it, for pausing, we can add the timedelta of the amount of time the opponent spent on their move to <white/black>EndDatetime. and instead of doing all of this, I could use timer.js lib instead. now my question is, is it too trivial problem to use a lib? i think one could just use it and save their time.
Graphql is really nice to work with, you won't need to ask your backend team to, say, include some fields in a response, you can just query realtionships
its not necessarily worse or better. graphql works on one endpoint while REST had many
I have had a few months of experience with graphql
There's a lot of things you have to consider when comparing graphql with REST.
Graphql offers a lot of benefits over rest, it exposes a typed and unified interface for your clients. You fetch exactly what you need with graphql. Which generally means you need to make lesser network requests with graphql
ye but the hype around gql was kinda overblown
its definitely really good ,but i dont think it will be replacing rest soon
But practically, I would recommend REST over GraphQL for anything you use in production, if you want to build with python.
GraphQL was released in 2015 which means it's a relatively new piece of technology. Fewer people use graphql- so you have fewer guides and resources to learn from.
What are best practices? What should I do with x in graphql? How do I validate input data?
There's no right answer to this yet, and wont be for the foreseeable future. You have to figure out what works for you on your own.
mhmm
The python graphql ecosystem is also not completely production ready, when compared to the nodejs ecosystem, though we have nice libraries like strawberry and graphene.
So IMO graphql in production is a deal with the devil
I spent a lot of months learning this.. lol?๐
What's qloom?
I couldn't find any related resources, sorry
Could u link some
And also I dont think this is the right place for adverts
If I have an api that fetches some data from another API for some features but otherwise does everything by itself (interacting with presentation and data layer), is it still a technically a gateway api?
eg my zoo api fetches images from dog, cat api before returning it to zoo.com
probably not
most web services use some sort of other service, for example a database
Yeah, i need to write a report so I was wondering if gateway is correct usage here, thanks for the clearup
hm what's graphQL?
An API query language.
It's going to take years for it to replace rest
It all depends what you want I suppose. I don't know if it has to replace it necessarily.
Hmm
Why not use both? ๐ค I heard some companies use graphql for querying data and rest for mutations
What's the point of using two?
rest has established patterns for, say, permission checks, validation. I don't see why won't you use rest with graphql if you want to
Hello
import platform
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chromium.options import ChromiumOptions
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.utils import ChromeType
Selenium setup...
if platform.system() == 'Linux':
opts = ChromiumOptions()
service = Service(ChromeDriverManager(chrome_type=ChromeType.CHROMIUM).install())
else:
opts = Options()
service = Service(ChromeDriverManager().install())
opts.headless = True
opts.add_argument('--disable-dev-shm-usage')
opts.add_argument('--no-sandbox')
opts.add_argument('--disable-gpu')
opts.add_argument('--remote-debugging-port=9230')
prefs = {"profile.default_content_settings.popups": 0,"download.default_directory": r"C:/Users/apskaita3/Desktop/Nasdaq_file/companies/","directory_upgrade": True} # IMPORTANT - ENDING SLASH V IMPORTANT
opts.add_experimental_option('prefs', prefs)
driver = webdriver.Chrome('C:/Users/apskaita3/Documents/New folder/chromedriver.exe',options=opts, service=service)
#driver.get(url='https://google.com')
driver.get('http://www.nasdaqomxnordic.com/aktier/microsite?Instrument=VSE95425&name=Amber Grid&ISIN=LT0000128696')
driver.find_element_by_id('exportIntradayTradesCSV').click()
time.sleep(5)
driver.close()
not works
What do you expect to happen and what happens instead?
My guess is the problem is with your crud but you haven't shown the code for that
Nothing session created
It's such a pain to get Selenium working in most environments, especially if you're not doing it headless. There is a Docker image, that's the most reliable solution I've found
how can i make a dm chat feature in django
i guess i
will need django channels
websockets
yep
can django projects be deployed in netlify
Docker can get download files automatically?
Docker is just a tool for building containers, you could try running that Python code inside a container with headless Selenium if you can't get it working otherwise. I personally find that easier then fighting with Selenium, but if you've never used Docker before either I don't know which path will be easier for you
Maybe, looks troublesome though https://answers.netlify.com/t/can-i-deploy-django-on-netlify/8783
Maybe try this instead https://help.pythonanywhere.com/pages/DeployExistingDjangoProject/
Deploying a Django project on PythonAnywhere is a lot like running a Django project on
your own PC. You'll use a virtualenv, just like you probably do on your own
PC, you'll have a copy of your code
yup i have read that it aint straightforward like it is for static websites
i found heroku better for deployment but thanks anyway.....
using datatables and trying to get my length button and filer in the same row, not sure how to manipulate the dom structure
I'm trying to make a navigation bar using HTML and CSS, does anyone have any ideas on why text-align: center; isn't working for me?
Is there any modern async web thingie that supports streaming uploads? I am using Tornado and I thought there'd been progress with Starlette etc, but checking it out it seems they hold the whole file in memory as well
I don't know what's hot and popping these days, I thought this would be a good place to ask
I basically want to receive a file over an API endpoint and put it on S3
last_build_date = Column(DateTime, default=datetime.now()) your default is incorrect, you shouldn't call now here 
You can use Enum(native_enum=False) here, it would store your enum as a string
Hey, I am a bit confused about how to proceed. Should I learn vanilla Django before going into REST framework?
If you don't plan to use templating, just skip the views/templating parts and move to REST framework for those. Routing and models is basically the same across the two paradigms.
In your case it would be whatever datetime.now() is at the start of your program, you can pass it a callable:
https://docs.sqlalchemy.org/en/14/core/defaults.html#python-executed-functions
e.g. datetime.now without parenthesis ()
np, i'm also learning a lot - i didn't know about this https://docs.sqlalchemy.org/en/14/core/defaults.html#computed-columns-generated-always-as
HI I just want to know where I would go to learn python
I know absolutely nothing and am trying to decipher old code
Thank you!
Is there a better way to do password input than just making an HTML form and password type input?
It's slightly concerning that this method just dumps the password into URL parameters and queries the URL specified in the form's action parameter.
Shouldn't be in the URL parameters on a POST, and hopefully you're sending over HTTPS
HTTP for now, I don't own an SSL certificate
Also I am not setting any info up for real, only test info.
HTTP if running locally in dev or even on a server without any important information is fine. POST should move it to the request body instead of the URL. Then, when you're ready and need to secure it, check out LetsEncrypt for a free SSL cert for HTTPS.
awesome
Oh my goodness, thank you so much for pointing me to Let's Encrypt!!!
ok, so here's what I have on the HTML side:
<form method="post">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password">
<input type="submit" value="Log in">
</form>
My route for this page:
@app.route('/login', methods=['GET', 'POST'])
def loginPage():
print('serving login page')
if request.method == 'POST':
print('login request with form data {}'.format(request.data))
return render_template('login.html')
else:
return render_template('login.html')
For some reason, the request.data is empty, why?
oh doi ๐ flask leaves that empty if other mimetypes succeed...
Hey @brave compass!
It looks like you tried to attach file type(s) that we do not allow (.html). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.
Feel free to ask in #community-meta if you think this is a mistake.
I got this working while reviewing this Stack Overflow link: https://stackoverflow.com/questions/5995405/how-to-center-a-navigation-bar-with-css-or-html#
.navbar {
width: 100%;
height: 45px;
align-items: baseline;
align-content: center;
margin: 0 auto;
text-align: center;
}
ul {
display: inline-block;
...
}
The links in the navbar all got centered when you entered that into CSS?
Hey @brave compass!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Yep. Here's my file: https://paste.pythondiscord.com/makovoqeme.xml
I left out the background coloring. If it's still not working then maybe it's something with the viewport (though that'd be weird).
Sorry, I need to run off to bed, but will check in the morning if it's still a problem and see what else I can think of.
I want to send a link in email which is going to trigger a get method. It is working perfectly in postman like that. But how can I include those headers to my link?
But it gives me this error:
{ "statusCode": 401, "message": "Access denied due to missing subscription key. Make sure to include subscription key when making requests to an API." }
how are you sending the request, with the requests library?
I am trying to send this request with a browser, the api is running on server.
Iโm a self taught developer, and I feel like Iโm missing something huge.
Iโve been through some Udemy tutorials, built real world projects for my business, and worked with JavaScript and python for about a year now, but I feel as if Iโm still missing something from my education of front end development. It still seems complicated to me and like I just donโt โget itโ.
Process goes like this:
Have problem thatโs needs to be solved, or idea โ> find a similar tutorialโ> make a extremely rough plan in my head โ> build something with a roll of duct tape and stack overflow โ> repeat
I almost feel like I can program but donโt understand computer science.
What books, guides, or articles can I read that talks more about theory and larger topics, beyond just a tutorial of โhow to use x frameworkโ? How can I start to see the big picture?
@wide anchor Find a problem you want to solve, then determine if what you already know is sufficient to accomplish it.
Realworld problems are the best problems to solve.
Yeh boss
you don't set headers in get requests created by browsers. So you cannot. You can use javascript and do a fetch and set the headers that way but you can't do a simple copy and past of the url into the url bar
Programmer don't ask such questions bro ๐ ๐ซ
In django + postgresql how can i get today's, tomorrow's and then next 7 days records respectively i mean, group them and get with annotation or something
"my business" << This is good as there is no one to fire you, you are free to try new things and implement them as you see fit @wide anchor
I envy ya ๐
what does this mean
Pro talks bro you can't understand๐คฃ ๐คฃ
I've been doing web development for about 6 years now and I feel like I'm only finally getting more of the big picture. It's mostly just been like you're saying, finding problems and panicking while searching for solutions that I don't understand
just keep looking things up and reading
Yea being the owner is great for sandboxing problems, but when it really comes down to it, I really want to be a better coder
Ohh that Great
So what do you want to accomplish first? What's a 30 second elevator pitch on the thing that needs solving @wide anchor ?
If you have some small work give me
I need to understand the principles of web development to make an archive of videos for my clients
An archive of videos can be telnet.
Why do you need principles, go quick easy fast, unless you want flash.
Do you want a problem to solve because you're bored, or a problem to fix because you need a solution.
Like:
How many requests to the db is too much?
Do I store the data in a local store (vue js) or do I fetch the data each time?
Other things like this
What is DB bro
Again, you sound as if perhaps youre searching for an unsolved problem.
sqlite3 or postgresql
No, itโs a feature upgrade for my clients on a non-software based company. I just love to code so Iโd like to code the solution so I can also learn more
You don't need django if flask works just fine, or perhaps python3 -m http.server even.
I love to code too; it's a great hobby of mine.
But I don't search for problems, i search for ways to solve problems using python and semi-maybe-mostly niche things.
i.e.
I donโt think there even needs to be a server component - just vue js and the database is my thoughts
but if you have the time it's definitely worth going under the hood and getting all the tiny details about a particular subject,
also, you should at least have a basic web server for an API to your database - the frontend should almost never talk directly with a DB.
So Iโm fetching about 1800 records in a firestore db each time the user loads up the site - and then the user will navigate using the sidebar to each video component - I was thinking it would be silly to refetch a video from the db if Inalready did
Hourly
So process flow is client request โ> server โ> firestore ?
Google sheets
For what ? What are you referring to here ?
The google sheets
do you have formulas in them pointing to cells within the sheet.
i.e. Can we export as a csv and do this better, and without uncle G looking over your shoulder.
If youre doing hourly Excel work, you're doing it wrong....
Excel is an output format only; executives and above.
So many companies, they do it wrong; painfully so. Oh the horrors......... =/
For this specific project, there is no google sheet. Just a folder of sub folders containing mp4s that need to be progmatically uploaded to Vimeo and stored in my db
What would this look like at a high level example ?
What kinda db; something on aws maybe?
Fire base
oh, you are wishing how to plan the process of developing programming product. planning the project in a... more industrial way.
System Analysis & Design comes to rescue
it teaches how to select projects, how to set requirements what needs to be done, how to design its use cases / scenarios from user view point, how to design data flow diagramms out of it, how to plan database model objects and how to design implementations of them, how to plan UI, how to plan efficient code structure by modules/packages for implementation and finally processing to implementation stage.
Amazing, so this will teach me the DESIGNING aspect of programming right ? But I would still need an โimplementationโ guide correct ?
mm yes, it teaches you how to design projects
But essentially it just give you sight how to do in a bigger picture
In order to design well technical parts you need to have a broad and deep understanding of core technologies
in order to design UI, you need to learn how to use tools like Figma for designing and all the reading how to plan interface in human friendly way
in order to implement / planning how to code well, you need to cover at least basic topics like:
Head First Design Patterns
Clean Code by Martin
unit testing principles practices and patterns (by Vladimir Khorikov), TDD
domain driven design by Eric Evans
and e.t.c.
Writing clean efficient code structure obviously requires learning different programming aspects how to do that
and all related good practices to it. Unit testing makes it the most amazing btw ๐
Well and obviously coding well requires a lot of practice. Books are just a knowledge that needs to be practiced in order being useful.
The System Design book just gives you plan how to that in a scope of industrial project. It does not make you an expect in every specialized field to do it in the best way
Ok this is awesome - thank you, so by reading these books I could use the principles taught in them to write better, more efficient code for web development ?
Surely. i am web developer as well
Awesome - Iโll dive into them. Thank you ๐
u a welcome. Btw, I went through university up to Master Degree but never was taught anything like this ;b Well technically i was, I remember going at least through one chapter of System Design
but basically I needed to self learn all of it after university too
Weโre these the most helpful books to you in your journey of self taught programmer ?
I love books, but books alone could not be helpful.
The usefulness was in reading books, asking advices here and in DevOps discord server and even in frontend discord server, and applying everything at practice at work everyday 8+ hours.
System Design and Design Patterns are sure memorably useful reading out of all of them
but it was just one among many.
I would stress again that learning Testing gives the best proffit in writing better code in a short time
in combination with a bit of DevOps tools like Ci/CD pipeline, Docker and e.t.c. it gives me the fastest development speed
without losing quality
Good to know, Iโve always dreaded testing and ignored it hahah
I would be lying actually that saying just a bit of DevOps tools are necessary.
Actually all of them are needed to reach full happiness. to have Infrastructure as a code.
My process of development reached a stage where
Once I submit code to repository
It is auto build into docker container by CI/CD pipeline
runs unit tests
redeployed fully automatically with whole infrastructure (servers and e.t.c.) into staging environment
it runs integration tests that all microservice applications part work together in unison
and then saved as ready for deployment in one click to production
Hi everyone, has anyone had a problem trying to connect MySQL in django 4.0 using macbook pro with M1 chip?
Speaking of planning and architecture
being good web developer requires learning stuff like that too
Hello, I would like to start developing a website but dont where to start. Is Django better or Flask?
and if so any tutorial suggestions?
planning stuff in microservices makes it planned for bigger scalability
and just having easier / smaller code in independent parts. Makes stuff sort of... quite easy, simpler.
it brings its own set of problems though
But higher level infrastructure tools resolve them
This is all awesome stuff, thank you for all of this - have a huge pile of books to go through now hahah
xD (looked at my own huge pile of books waiting ahead of me, the road never ends)
?
ill start with flask!
and just going faster due to having everything out of the box
thank you for your help
highly recommend this tutorial.
it was recently updated to flask 2.0
Great!
ill get started right away!
This is a huge help you guys thank you so much
hello I was thinking of getting into web app development but Idk what roadmap should I choose
I will prefer if its related to python libraries like django or flask
should I just go with full stack course python oriented?
btw for roadmaps: https://roadmap.sh/
considering that you ask about it in python Discord server, you are going to receive the most biased answer:
I think starting from python backend is the best option in terms of getting fastest development with being introduced to core programming concepts better
frontend is just not giving the same best practices efficiently IMO.
and switching from backend to front should be easier that from front to backend.
and I am biased to frontend ๐ even if i cared to learn/practice it
ty also any paid/free tutorials for this which u recommend
because I am looking for all in one thing
which teaches pwa , frontend , backend (with python)
So you aim to be developing frontend and backend separately?
frontend in frontend frameworks, backend in python?
it is impossible to learn everything in one thing.
I can recommend starting from Flask or Django
https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
https://docs.djangoproject.com/en/4.0/
with moving into
Flask Restful
or Django Rest Framework https://www.django-rest-framework.org/tutorial/quickstart/ for those purposes
yes like I was checking some bootcamps for "full stack development" in udemy
bootcamps teaching full stack are usually a lie ๐
oh
for Frontend I would recommend React / Angular or Vue.js
Vue.js should be easiest out of them
To get started in frontend learn HTML/CSS first, this book is amazing
Then progress into learning Javascript
And then start doing Vue.js from docs
https://v3.vuejs.org/guide/introduction.html
and getting advices in Vue community
https://discord.gg/vue
Optionally getting started from book as well
The easiest way to setup Vue.js project, is Vue Cli 5 tool
https://cli.vuejs.org/
it will setup everything with SASS and e.t.c.
Vue.js - The Progressive JavaScript Framework
๐ ๏ธ Standard Tooling for Vue.js Development
thanks
mind you, that you are just learning frameworks and nothing out of programming concepts in those materials
mhm
bad code would be for sure ๐ u need to learn more than that if you wish to be good
๐
have you messed around with Vite? i've used both and was wondering if you had any preference between the two
Initially used during starting docs, and then abandoned in the favour of Vue Cli 5
Vue Cli 5 was setting me up everything from zero to fullest capabilities, including how the f*** to do testing, and offering in CLI interface all tools for all categories with bolierplated code.
I did not really learn how to do the same in Vite
I guess i missed that if it can do the same too
Yeah i think you're right about vue cli having alot of good boilerplate code with everything you need to ready to go, setting up things like vuex or vue router is a real pain with plain vite. thinking of going back to vue cli 5 even if it means slightly slower build speeds.
can i save form data before entering into the database. Means i want to save the form data and i want to create a entry only if the payment is successful.
django + react
yes
stripe api
but how can i save form data. I can save the api data from stripe directly.
Heroku/Django
I Had an SQLITE configurations on the settings.py, why is this not working? Ive also changed the ENGINE to postgres in the config vars
This is my django settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
So, suppose i have a job model. How can i call this job model? after the payment is successful? means i understand that i can use the data and store directly into my database. But what about the data which i need from the frontend form? How can i call that data after the payment?
because customer data will be provided by stripe
so its easy to save directly.
so for example: I have name, age and address. I want to save this data from the frontend after the payment went through.
maybe wrong example.
suppose i have job title, salary, fulltime, location data. How can i save this data? this data is different from stripe api data.
Hello im trying to upload from my front end to my back end server with flask
and i have an issue
that when i pass the file i dont get the file to my back end i get an empty ImmutableMultiDict([])
If I update Jinja without updating django will it create problems?
As far as I know Django uses its own templating language by default.
So updating Jinja should be completely safe
thanks
Someone know what should I use for parsing a database from a website? Iโm working with python
that sounds weird. Could u rephrase what you are doing
hey guys. Im new to this field. Can I create a Python website with a personal account where the user can find only the information that I allow?
Sure. So, I have a school project and I need to look through prospects of different types of drugs to search some keywords in order to find an interaction between drugs. And Iโm working in python and my professor told me that in order to do that I could use a method called parsing. I donโt really know what that means so I was thinking that someone can explain or give an example or so.
in which form he gave you information about drugs
how your source of data looks like
He told me that I need to extract data from a database in which I can find all this prospects. Iโm still looking for that database because I have to do it for my country specific and it is quite difficult to find here.
how the database looks like
was it given to you
Nope. And I donโt know yet how the database looks like because I couldnt find it yet. I was hoping that I can least find what parsing is
parsing can be done in different ways, since you don't know how your database looks like, it is impossible to say which method of parsing you need
I would assume that you will probably find database in the form of csv documents with data separated by ,
highly likely all you will need to upload database, just reading lines and applying split function by delimiter ๐ it depends on how it is structurized
technically there is so called web parsing, but i think highly likely, you don't need it
Ok, I understood. Appreciate your help
Hiii. I am currently building a notes taking website with django, pretty basic one. I added the note creation and deletion functionality succesfully and also added the login authentication functionality. But there is one thing i am struggling with. I want to show a user only his notes not every else note that exists in the database. Any idea how that might be done. How should i design a model or write a view for that. Would really appreciate the help.
You need to send the user's information in the request to the server to then pull the objects with only that user as the author.
usually your function is like def notes(request):
the request holds that user information
I am using 2 datetimes to the future called deadlines, and use it to calculate the times remaining for the timers for both players in chess. I get that deadline in isoformat from server after every move is played. my question is how accurate are 2 devices time when they are set to automatic date and time?
Wouldn't the times always be posted according to server time? So it should be 100% accurate I would think, unless I'm misunderstanding the question.
selenium.common.exceptions.WebDriverException: Message: unknown error: DevToolsActivePort file doesn't exist
i give the datetime of deadline when the time will end and use current time on that machine to see how much time left every x milliseconds
so there will not be any latency issues
Ah, no idea, might be a good question for game dev.
Would I be able to ask a question about relative paths here? (html+java noob)
I think this is more python focused but we can try to help maybe?
How come my new site is loaded perfectly fine inside postman, but in browsers I get ERR_CONNECTION_CLOSED
DNS is set up...
wait, do .dev sites require HTTPS? ...
They don't, no.
Or wait, I mean working in dev, meaning locally, doesn't.
You getting any kind of more specific error than that?
Is that when you're fetching data?
I asked in a help channel, but it ended up going dormant!
this assignment is purposely meant to have unorganized files, with the intention of us using ..\ to get the img src to work! I was able to fix the navigation id from character page.html to go to index.html using ../../index.html
But I cant figure out the img pathing
\ path is not valid linux filepath format. the end of the story.
I'm sorry, this is my first week of the course (and im learning remotely for the week due to being sick)
can you explain that a bit?
do you specifically mean the backslash?
as far as I know browser paths can be possible only in two formats
Absolute and Relatives
absolute - /src/blabla.jpg
relative - blablabla.jpg
relative - ../blablabla.jpg
it is not possible to have \ file paths for web site
oh that path isn't to a website! It's a relative path leading to a local image file
unless perhaps windows filesystem allows it for local file paths? ๐ค
yea!
u use it in HTML language
HTML usually means web site ๐
file-paths-incorrect\main-images\header-images\neit_logo.png would be the full relative path
but it doesnt work since character pages.html isnt in a shared folder so we need to use ..\ to get it to work
(we arent allowed to move files manually, since the sake of the assignment is the pathing)
in order to find correct relative path...
as far as i understand u a using plain HTML without frameworks, right?
just open console in the folder of your HTML file that has links to images
uh correct, for example
<main> <header> <img src="..\..\..\main-images\header-images\neit_logo.png" alt="NEIT Logo"> </header> <hr> <nav> <a href="../../index.html">HOME</a> | <a href="characters page.html">CHARACTERS</a> </nav> <hr> <section> <h2>Monsters</h2> <img src="images\monsters\alien.jpg" alt="Alien"> <img src="images\monsters\godzilla.jpg" alt="Godzilla"> <h2>People</h2> <img src="images\people\macho man.png" alt="Macho Man Randy Savage"> <img src="images\people\mrt.webp" alt="Mr T"> <!--Image with absolute path--> <img src="https://vignette.wikia.nocookie.net/monstersincmovies/images/0/09/Sulley_002.jpg/revision/latest/scale-to-width-down/340?cb=20130512141939" alt="Sulley"> </section> <hr> <footer> <img src="..\..\..\neit-tiger.png" alt="NEIT Tiger Mascot"> </footer> </main>
and find a path by hand from current HTML template to images
or by console
cd ..
dir
commands movements ๐
basically images need to be accessed relative to location of your HTML file that has the links to them
well, or just using absolute paths, which would be easier. but since assigment is not allowing it, lets do it relative ๐
yea we have to do relative, and we can't move files/folders. I have to have the neit_logo.png img src to display in the character page.html file by changing it's directory path using ..\
Is that what you're trying to explain?
file-paths-incorrect/main-images/header-images/neit_logo.png
pages/characters/characters page.html
?
assuming trying to find path from this html to png
../../file-paths-incorrect/main-images/header-images/neit_logo.png
it will be basicallly something like this
.. - means going to parent folder
we moved twice to parent folder
and then moved to subfolders of going to png
u got ur answer bhai?
yea for example I did ../../index.html for a navigation link to go to index.html from character page.html
btw, i would highly recommend renaming characters page.html to characters_page.html
not allowed
it just looks so gross with space. not sure why
oh my gosh I fixed it. I see what you were trying to explain.
Original relative path: file-paths-incorrect\main-images\header-images\neit_logo.png
fixed: ../../main-images/header-images/neit_logo.png
I was doing this the whole time:
..\..\main-images\header-images\neit_logo.png
I didn't realize I that I was allowed the change the backslash to a forward one... ๐ฐ
I can't think of a situation I ever use a backslash in web dev.
And I've worked on both linux and windows machines.
they do
as soon as I fixed https it started working
chrome & firefox enforce it
Yea, I thought you meant working locally in a dev environment.
๐คท๐ผโโ๏ธ
That's surprising though, because I've been told https is only really necessary for websites using sensitive information.
why not enforce it on other tlds then
That http isn't a problem otherwise.
should, sure.
unless you are developing some micro services
for internal use only
but then I recommend gRPC
everything should use ssl
I hope dns over https becomes more widespread too
yeah, the dumbest thing ever
chrome won't open .dev in plain http
it refuses
lol
same with ff
I was like wtf why curl works but chrome errors out
just google things
Oh I see, google bought it and now redirects traffic to https in chrome.
Is there a benefit to the .dev domain? Instead of dev.yourdomain.whatever?
there ain't any benefit to any tld over the other really, except name and SEO
but I wanted a .dev for my personal website
I was wondering do people Still prefer website which are made from html ,css,js considering the fact wordpress Exists?
lmao
Yea, much so.
I can count 10 reasons at the top of my head
first of all PHP
second of all WP
it's all shit
You can't build an advanced custom web app in wordpress.
you can actually but it's hell
Yea WP is really slow.
and WP uses that same tech (HTML,CSS,JS)
so it's basically just another framework
but for beginners
a "CMS"
Because nowadays people make website using wordpress( probably earn good amount too) then label them as web developer so I was just confused.
naaah, publishing a WP site ain't web dev
it's like writing a blog
lol
if you write custom wordpress plugins and such then you are a dev.
Yea I've seen plenty of web dev job advertisements where they use wordpress. I suppose technically, sure you're developing a website, but you won't get any advanced apps coming out of that. At least I don't know of any.
At my last job we had a lot of WP sites that were very customized
I hated it all
but publishing content for WP ain't web dev.
they probably just use it so they put it in an ad
at the least you should be comfortable with PHP
I have a few images in my html file with <img> tag. When I load the html in flask using render_template, everything else gets loaded instead of the images. Can anyone tell me how to fix this?
Please ping me when u reply
Share your code?
yes plz share ur html code.
How do I have an idea to make a 3d lol game you want too much memory from the server?
This is like, 5 sentences in one.
:/
are you trying to make a 3d lol (league of legends?) game and are wondering how much memory the servers should have?
yes
ah, #game-development might be a better place to ask about it? either way i don't know enough to help further than making sure people know what you are trying to ask
okeu
just getting started with django, I kinda get the basics and working on a site to display content, how would I go about (or what should I search for) daily querying a site to refresh data for the app?
going to look into django-cron but open to other suggestions
I am making a Flask web app. What's the best way to update the contents of a page every second or so?
Can i create game in unreal engine and put this on web?
Celery are good for background tasks, but it might be complex for this case (I mean it requires extra process (worker), looks superfluity for only daily query)
Maybe u have to check Django Dramatiq, but I haven't had experience with this
This is asked frequently, please search the channel
ok
Why is a web server needed? Wouldn't it be the same of doing something like somewhere.com/index.html?
hey guys!
I'm having a strange problem with flask sql alchemy, please check if you can help me, I'm stuck
How to create a many-to-many relationship with 3 tables using flask-sqlalchemy? the default docs only work for 2 tables, not 3.
Thank you!!!
the result of the table would be
id | table1_id | table2_id | table3_id
Maybe the M2M could relate to a through model that has 3 FKs?
I'm not quite picturing the scenario. Can you describe how the models would interact?
Ok so I'm using Flask's session plugin and need to test having multiple users logged in at once. For whatever reason, I can't use my phone for this because my college's network is set up funky and my phone can't see my laptop. Is there any way to isolate two Firefox instances to allow me to do this?
start an incognito session
good idea
thanks, it worked!
Does flask-socketio respect flask-sessions or do I need to do funky stuff for that?
Hey @snow edge!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
I have a basic Python desktop app I need to convert to web app since I can't get on mobile stores quickly enough due to an earlier than expected release because reasons. What's the quickest and dirtiest way to do that?
I think it's some variety of flask or django? Shove me in the right direction. Please. Not expecting miracles and it needn't look pretty.
Hi, I'm using Django and I have this function on one of my models
def diferencia(self):
dif = self.likes - self.dislikes
return dif
and then using it on a template to show the rating of a post, but I wanna make a query which order the posts lists using this rules of likes-dislikes but I don't know how to do it
posts = Secret.objects.order_by('likes')[::-1]
and this is my query right now but I don't know how to make the query properly
Guys can I deploy flask app on a local machine. It keeps crushing when I ran it in development mode for a longtime example after 2 days whereby it a method that runs in the background after every one minute.
you want to use https://docs.djangoproject.com/en/4.0/ref/models/expressions/#f-expressions and annotations
probably something like py qs = Secret.objects.all().annotate(diff=F('likes') - F('dislikes')).order_by('-diff')
probably reading something about REST API
https://www.amazon.com/REST-Design-Rulebook-Mark-Masse/dp/1449310508
A whole book about it, reviews look good, almost 5 starts out of 5 for 100 reviews
I was trying to create a login system using django
but when i try to log in
literally nothing happens
i thought maybe what if it doesn't even receive the username and password, and that is what is happening according to me
coz i printed it
and i saw this
it returns None None
so can someone help me in figuring this out
https://www.oreilly.com/library/view/monolith-to-microservices/9781492047834/assets/cover.png
Speaking of design, perhaps to read this too also. Sort of important regarding backend APIs too
- Perhaps the book "Building microservices"
hello
lets say we have a json first time we cache it.. second time we gonna cache it it has changed, now how can we get only the new data. Mind that some been replaced, or been deleted
Hello,(Django rest framework) does anyone knows how to send custom errors to the frontend. I know (try-except) and if (except) return a Response, but does that returns that response if theres a 500 error when requested for the frontend?
{"clips":[{"name":"18758979.mp4","time":"48 minutes ago"},{"name":"987654.mp4","time":"46 minutes ago"}]}
maybe i can just pull name, and somehow save a list of the latest one, if its not same then == new item
from django.contrib import messages
messages.success(request, 'Your Message has been sent!')```
Something like this i guess
but thats on django templates I think right?
with setting caching in python framework at Redis caching level, you can setup any type of cache validation rules your imagination allows https://pypi.org/project/redis/
from rest_framework.response import Response
@api_view(["GET", "POST"])
def get_ping(request):
return Response({"message": "pong!"})
if u wish sending error, just change response to have appropriate http error status code
return Response({"error": "my custom error"}, status=400)
or if you wish even more clarity and following best practices
import rest_framework.status as status_codes
return Response({"error": "my custom error"}, status=status_codes.HTTP_400_BAD_REQUEST)
Thats clear, Thanks!
I've got my flask views like this:
app = Flask()
@app.route():
def create_todo():
return _create_todo(...)
def _create_todo():
# service function
pass
Here I've got a naming clash between my services and routes. Is there a better way to name them?
Please ping me when help!
You could encapsulate your logic into a Service/Command class
e.g.
class CreateTodoCommand:
def __init__(self, session: Session):
self._session = session
def execute(model: CreateTodo):
...
@route
def create_todo(model: CreateTodo):
command = CreateTodoCommand(get_session_somehow())
command.execute(model)
For simple crud service would probably be better but i'd use command if you have some complex logic
Hello folks,
I currently have a flask app deployed on pythonanywhere and I want to add celery to the arsenal, but since pythonanywhere has no support for that, i need to migrate.
What are the service I could use that would provide a server for the workers and a redis broker ?
I think you can go with any vds
The thing is, I won't be migrating the flask app from pythonanywhere, I just need to distribute the tasks so I'll need a remote broker as well.
For the flask app to be able to send the tasks over to Redis
You still can host your services anywhere, but it think there are managed solutions too
Exactly, I'm asking about those managed solutions.
And if anyone has any recommendations, etc...
#help-candy please
I'm just saying you don't have to use a managed solution since you can just run redis on a vds 
Didn't have any experience with managed redis and other services, so i can't recommend anything
Alright, thank you !
I have another question here, if I get a VPS/VDS instance for example on provider X, how can I hit the local redis instance from my flask app ?
Well, it's not local if redis is on vds and your app is on pythonanywhere ๐ค
Thank you very much
just raise redis with docker/docker-compose at this VPS
and it will become local to your flask app (for easiest setup I would recommend putting flask to docker-compose too, so it would be right in the same docker network, which will make domain address to access redis, same as the service name in docker-compose)
I'm actually doing this currently
Wondered if I could have plain service functions
That requires migrating the flask app from pythonanywhere
Which is not what I want to do
Use whatever you're most comfortable with, i find bare functions hard to track/manage
hey anyone here?
ok
i need help in registering my model onto the admin site in django
i think i did everything correctly
but the database is not popping in the admin site
@golden bone
show your code
Please stop pinging me, if someone can help they will
I was encouraging you to ask your question... I don't know Django too well but it looks like your migration worked
yeaa
I don't think models automatically show up in Django admin, you might need a Model admin class ?
admin.ModelAdmin
Yeah, check the docs,.I think that's what you're missing
ok thanks a lot man
Hi, Nice to meet you
hello
you solved your problem?
r u really good with django?
In order to see your user table on admin site , you need to register model
yep did that only
and you can check your admin site.
yes i did
but it was not there
if u r open to join a vc or something i can screen share
I just want to make auto making thread / creating list. I just checked in console, the error says
"{"error":"Unexpected token u in JSON at position 0","version":"1.3.0"}".
How can I resolve this error?
The Python Code:
import requests
from io import BytesIO
headers = {
'authority': 'traderie.com',
'method': 'POST',
'path': '/api/adopt_me/listings/create',
'scheme': 'https',
'accept': '*/*',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-US,en;q=0.9',
'authorization': 'Bearer ',
'content-length': '722',
'content-type': 'multipart/form-data; boundary=----WebKitFormBoundarypqN01X2kArSkOHBn',
'cookie': '_ga=GA1.2.850822138.1642224893; _gid=GA1.2.556027755.1642224893; usprivacy=1---; ad_clicker=false; _pw_fingerprint=6818da724c1a866373d3104d2cd082e4; _gcl_au=1.1.628091182.1642224893; _hjid=cc106801-cff3-4156-afad-2b5845f96325; _hjSessionUser_2441420=eyJpZCI6IjQyMjdmMjVjLWEyMjItNTI1Ny04NjUwLWY3MmU1NjEyYjNlZiIsImNyZWF0ZWQiOjE2NDIyMjQ4OTMyMDAsImV4aXN0aW5nIjp0cnVlfQ==; _hjSession_2441420=eyJpZCI6ImVkODE1MDc5LTYwNWItNDIzMC1iODUxLWZkOGRlNmM2YjM3MCIsImNyZWF0ZWQiOjE2NDIyMjQ4OTM0MzEsImluU2FtcGxlIjpmYWxzZX0=; _hjAbsoluteSessionInProgress=0; _pw_audience_segments=["1","3","4","5","6","7","8","9","10"]; __stripe_mid=a848c4df-5112-4afd-8bdd-2235857cc00abc7ef9; __stripe_sid=e1c6337b-f03f-4b93-8441-eb1d118cee58001fb3; _pw_audience_categories=["games_hardcore"]; _pbjs_userid_consent_data=3524755945110770; pwUID=369796799639702; __gads=ID=dcb867edd8f2877b:T=1642224926:S=ALNI_MYArRYYa1oDgieG9f1YFUuJjVv-oQ; G_ENABLED_IDPS=google; G_AUTHUSER_H=2; _gat_UA-176465218-1=1; _gat_gtag_UA_176465218_1=1; cto_bundle=5p2Tj182VmVrbFhLNUFmS3lZNXllZnk2b1UzbkYwR0JhVUFUMSUyRnplYWd1QWh1VyUyQmlrJTJGYjlOTU1XdE1xb050NjhHJTJCajczQW1MeDNQSnRoRG9tM2UzeHN1blk5Z2pHYllDUlJLQUxVUHVDclp1JTJGT0N6cHluWjdjZzRGNVdRZFhqeUJiQmZSZlVORnI0dGlhdnV4MDQ2YnZFeVVnJTNEJTNE; playwirePageViews=16',
'origin': 'https://traderie.com',
'referer': 'https://traderie.com/adoptme/product/1276977709',
'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"Windows"',
'sec-fetch-dest': 'empty',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'same-origin',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'
}
body = '{"acceptListingPrice":false,"currencyGroupPrices":[],"diy":false,"endTime":"","free":false,"item":"1276977709","itemType":"pets","makeOffer":true,"needMaterials":false,"offerBells":false,"offerNmt":false,"offerWishlist":false,"offerWishlistId":"","selling":true,"standingListing":false,"stockListing":false,"touchTrading":false,"wishlist":"","amount":1,"properties":[{"id":1,"property":"Flying","option":true,"type":"bool","preferred":null},{"id":2,"property":"Rideable","option":true,"type":"bool","preferred":null},{"id":9,"property":"Age","option":"Full Grown","type":"string","preferred":null}]}'
resp = requests.post(f"https://traderie.com/api/adopt_me/listings/create", data=body, headers=headers)
print(resp.text)
why am i getting this error, when even this error page clearly states that /register exists
you need to add "register" in url.py
already done that
i think the problem is with the keyword register, i just tried signup instead of register and it worked
noo
thats weird
coz i tried private window
and this works
but the normal window is putting a / in the end for some reason
so need to figure out why its doing that
fixed it by creating another app for register
Hello guy . Please someone can share with me a good roadmap to learn efficiently mobile app.I really need it.
@api_view(['GET','POST','PUT','DELETE'])
def testView(request, id=0, get_type='all', title=''):
if request.method == 'POST':
return Response("THIS IS GOING TO POST(CREATE)")
if request.method == 'PUT':
return Response(f"THIS IS GOING TO PUT(UPDATE) THE ID {id}")
if request.method == 'DELETE':
return Response(f"THIS IS GOING TO DELETE THE ID {id}")
if(get_type == 'all'):
return Response(f"THIS IS GOING TO GET ALL BECAUSE THE GET TYPE IS {get_type}")
if(get_type == 'one'):
return Response(f"THIS IS GOING TO GET ONE BECAUSE THE GET TYPE IS {get_type} WITH THE ID {id}")
if(get_type == 'group'):
return Response(f"THIS IS GOING TO GET A GROUP BECAUSE THE GET TYPE IS {get_type} WITH THE {title}")
return Response("none of the functions worked..")
is this a good practice?
Ive just put a response for earch not the thing I want to do but just for showing the code and to be more clear
I prefer the class based views for this kind of thing
think about if you should be using elif. Even if the functionality will be the same, the logic is easier to follow if you use elif
hello I am looking for help with this question I just posted in stack overflow - https://stackoverflow.com/questions/70792589/chromedriver-not-opening-django-development-server. Thanks in advance!
I agree. Function based views are mostly repetitive and unnecessary.
Function based views are fine, mashing multiple methods into single function is not ๐ฆ
That's the problem with the function based views. They get messy pretty fast. While it could've been done with CBVs much more elegantly.
You can use GenericViewSet in this case, as it seems.
https://www.django-rest-framework.org/api-guide/viewsets/#genericviewset
Django, API, REST, Viewsets
Okay thanks!
That's because of the APPEND_SLASH setting. You must add a slash at the end of the URL as a best practice.
https://docs.djangoproject.com/en/3.2/ref/settings/#append-slash
It could be better to use ViewSet in case you need custom logic and not just operating your models 
Oooh okay thanks
It inherits from what class
rest_framework/viewsets.py line 217
class GenericViewSet(ViewSetMixin, generics.GenericAPIView):```
Depends on the context but I didn't advise GenericViewSet because of the code block because that's for showing purposes, obviously. I advised GenericViewSet because he uses and wants to use multiple HTTP verbs, which is a perfect use case for it.
So why use GenericViewSet over ViewSet here?
Because he also implies CRUD operations, which can't be done without a model?
It depends
Generic one also provides most of the necessary logic for CRUD operations, which is a big plus, since he won't repeat himself.
Well, having CRUD already written for you is obviously nice but often you need custom logic anyways
You can still override those logic in the relevant methods. Still much easier with Generic one.
Don't think so
Your requests might not map to your models 1:1
I don't think he's going to rewrite all the methods for the relevant HTTP verbs. That's not the case most of the time.
Can you be more specific?
Simple example using a Post model: when creating it you might want to link it to the user, perform custom validation, etc.
Having that logic in a serializer doesn't seem to be right imo
Why? That's the perfect use case for the serializers. Since validations are purely meant to serializers. In normal Django, we use forms for custom data validation and in DRF, we use serializers.
Also, serializer's create method is also perfect use case for it. Linking the user.
If you need to perform a validation based on database state (e.g. user can't have more than 10 posts) would you put that into a serializer? ๐คจ
Where would you put that, and why?
Into APIView/ViewSet method or a service function/class
Because?
Because this way my business logic does not reside in serializers 
Also it's would be easier to test
Agree to disagree. ๐
Imo having multiple responsibilities in a serializer is not really a good thing
It should validate incoming data, that's all imo
I don't think so. Think of forms (which is the exact representation of serializers in DRF). Forms do not only validate the incoming data. They mostly do all the necessary validation of the related models.
Tbh forms and serializers are different things, though, they're similar
Also serializers are generally hard to work with compared to say pydantic models
The official documentation doesn't agree with you.
https://www.django-rest-framework.org/api-guide/serializers/
Django, API, REST, Serializers
You can see references of forms in that single article multiple times. To make it clear serializers are mostly the same of the forms.
Official does not mean i agree with it 
Why would single entity have multiple responsibilities?
It's generally bad
This conversation isn't going to some meaningful and senseful point. So no need to keep it.
I really don't understand why you should perform anything beyond validation in serializers
does anyone know what text editor i should use
VSCode is the most popular code editor
any text editor can be used, so just use one that works for you
I use vs code, or if I'm working command line-only I'll use vim, but I've seen people use notepad++ and several others with no issue
Sublime too
I think PyCharm and VSCode are most popular atm
Ok so I have Flask-Session and Flask-SocketIO running together. Currently, when I run emit() inside a @socketio.on function the client that sent the signal that triggered the function is the only once to receive it. How can I emit() to all clients as well as to only the one client attached to a session?
Hello, I'm using Selenium to automate a purchase on a website. I'm not trying to automate captcha or anything, I just want to be able to input the captcha and then for it to move on.
Currently, I'm using ImplicitWait, but after completing the hCaptcha, it leaves me on the same page.
Any idea how I fix?
this is basically it
wait 40 seconds for captcha to finish, then continue however it doesn't allow that
it's just stuck on here
any help is appreciated :)
Can you try to get whatever url you want after that?
You can also try waiting for the xpath instead of relying for the implicit wait
Hey guys, Iโm looking for a 0 to 1, beginner to advanced JavaScript book that is written for people who already know how to code. Any senior devs in here have a good recommendations ?
async def image_get(image_uuid):
if image_uuid != None:
image_link = "https://media.valorant-api.com/weaponskinlevels/" + image_uuid + "/displayicon.png"
return RedirectResponse(image_link)```
How instead of returning a redirect can i get the image and relay that without a redirect
not a senior dev by any means but specifying what languages you coded in before may help others recommend
Not really to advanced advanced level, as it is impossible to fit it into one book
But the best covering beginning stuff
Iโm great at python, and I can get my way around JavaScript, Go, and Rust
But Iโm not great at the last 3
Thank you again, I will check it out ๐ฏ
Heads up for anyone testing multiple sessions in a Flask app and using Firefox to test: If you open multiple windows/tabs, they will share cookies and therefore share the session. Two Private windows are the same way. If you open a normal window and a private window, you can test up to two sessions at a time, but no more..
Could someone tell me some designs for my website?
ah you see, I get the checkout link, and then I expect the human to do the captcha within the 40 seconds, then it will continue
the issue is that after completing captcha, it just stays there
Thatโs the way cookies in browsers are expected to work?
Multiple windows and tabs of the same browser will use the same session
Most probably wrong channel but has anyone written a Firefox add-on with Python or does know if it works and can point me to a tutorial or something?
Apparently it is not, need to do it in JavaScript
if anyone has worked previously with selenium please take a look at my problem in #help_crossaint
what could be causing this error in django
It should be request.POST, not request.post
python is case-sensitive
ohh yeahh that was the error
thankss
Right, so that's why I suggested that you tell Selenium to load the page you want after that.
Hello Guys,
I'm currently working with a python project that needs to integrate a SOAP based WebService
and i need to upload images with MTOM.
I've been searching for libs that i can use to deploy, but i'm not finding anything.
Does someone knows or have any official/alternative method that works in this case?
Hiya I am trying to run an python httpserver on localhost, what could cause this?
Im trying to run a python htttpserver on localhost. I created an index.html to show an opedata map. I can see the map, but some of its either white/gone, or it doesnt line up correectly. What can cause this?
eee
Hi guys, i'm trying to pass an url as a parameter with django for a view function, but i cant' manage to do it and i haven't been able to find anything online
If i try to use any other string it works as intended, but it's for an url shortener, so i need to pass links
maybe use a query parmameter?
{{base_url}}/add?url=https://www.google.com
Don't forget to urlencode it
i'm gonna look that up