#web-development
2 messages · Page 28 of 1
So shouldn't there be a relationship between that form data and the stuff they're ordering?
Specifically, I'd say doing something like... And someone correct me if this is bad design here
- For each order item (so the pizza), create a relationship to the order (e.g. the form data)
- On the form data, add a method to get all order items referencing the order (this is basically a calculated field and would use a query)
- Add that method to what's displayed in the admin panel.
For steps #2 and #3, see this: https://books.agiliq.com/projects/django-admin-cookbook/en/latest/calculated_fields.html
Ok, i'll try that.
Hm, wait
I don't get the first part
I have a model with foreign keys to both pizza object and user form. So I already have those.
So you have a third object that foreign keys to both?
yes
What if they want more than one pizza?
And it adds its own data as well
class OrderItem(models.Model):
user_form = models.ForeignKey(Order, on_delete=models.CASCADE)
item = models.ForeignKey(Pizza, on_delete=models.DO_NOTHING)
size = models.CharField(max_length=100)
quantity = models.CharField(max_length=100)
Size and Quantity are fields it gets from json since that's user choice
So for each order, with the way you've designed it, you have...
- One user_form
- One or many Pizzas.
- One or many OrderItems (equal to the number of Pizzas)
Yes?
not just for each order but for each item in the order.
say, if a user were to add 3 types of pizzas to the cart and then make that order, there are 3 objects created, for each pizza.
And they all contain a link to related pizza object, user form and user choice of size and quantity
Three Pizza objects. For the order, right. But also three OrderItem objects -- one for each pizza. Correct?
pretty much
Well, OrderItem is referencing to each pizza so Pizza objects stay the same
Let me clarify.
Say there are 5 pizzas on the website, each can be created in the admin panel. Then when a user orders a pizza, there are still 5 of them. But OrderItem now knows which one the user chose.
Ok. So this is not a dominos create-your-own topping kind of thing. Management provides the menu
I could post my code if that helps
Sorry I thought this channel wasnt in use
@prime ridge yep, it's a basic web-store. It could have been shoes instead of pizzas. 😄
I'm starting to understand the reasoning behind your design decisions (my brain went to "oh well why don't we [do what you did]") but I think this could be simplified 
But there are multiple OrderItem objects for each order and I still don't get how to group them into a single item in admin panel
Django's a little funny about storing lists, right? Like, if you could have a list or a dictionary field, you'd just need one order object for each order.
Those fields actually exist but they're specific to PostgreSQL (https://docs.djangoproject.com/en/2.2/ref/contrib/postgres/fields/)
Yea, but because I have those extra fields: size and quantity, it makes it tricky so I decided to separate those objects
Instead of having a list of pizzas and several sizes and quantities.
I have been working with sqlite thise whole time. Databases are out of my knowledge so far.
Nah but I got that from another discord
So, okay, let me just try to solve the problem as you have it instead of, erm, trying to tell you how you should redesign your entire project, gimme a sec to think
All OrderItems reference one user form. So the user form is the common element shared between all things relating to the order
I mean if that's poor design choice, I'd like to know how to not make that mistake again.
as mentioned before, you can add a calculated field to the user form model (call it an order model)
to get all OrderItems that reference it (a django query)
(this was step #2 above, maybe slightly modified)
then just add that field to the admin panel (step #3 above)
Ok, so I can display my Order objects in admin panel and then inside them have a list of related pizzas?
(assuming user form data == order) yes
Do i do it with Inline?
Here's my code, to be on the same page:
class Order(models.Model):
name = models.CharField(max_length=100)
phone = models.CharField(max_length=100)
def __str__(self):
return f"{self.name}, {self.phone}"
class OrderItem(models.Model):
user_form = models.ForeignKey(Order, on_delete=models.CASCADE)
item = models.ForeignKey(Pizza, on_delete=models.DO_NOTHING)
size = models.CharField(max_length=100)
quantity = models.CharField(max_length=100)
def __str__(self):
return f"item = {self.item}, size = {self.size}, quantity = {self.quantity}" \
f", order = {self.user_form}"
I had something like this I implemented very poorly and ended up hating it but lemme go get the code while you do that
right. So you'd add a method to order to query all OrderItems with user_form referencing that order object -- lemme see what I can dig up
def flags(self):
return Flag.objects.filter(event=self.id)```
So, modifying this...
def order_items(self):
return OrderItem.objects.filter(user_form=self.id)```
You'd add that method to order
Ok, yea, that worked... Not perfect, but at least it's definitely closer to what I wanted to have
Here's what I did to my admin.py
class OrderItemInline(admin.TabularInline):
model = OrderItem
class OrdersAdmin(admin.ModelAdmin):
list_display = ('name', 'phone')
inlines = (OrderItemInline,)
admin.site.register(Order, OrdersAdmin)
Let me show you a whole lot of ugly. I hate this thing but it should give you some ideas
Key part of this: I added a readonly field called "flags_html" which basically iterated over all of the related flags and provided a list output of them. The point is, you can override the HTML output handles the field you tack-on
so, if you don't like what it says or how it looks, there are lots of ways to override it
but yeah the way I did it was not pretty
Ok. Well, I'm trying to use standard views as much as possible. Didn't have to override any html yet.
Since I don't know natural limitations of Django so far.
Yeah neither did I which is probably how I ended up with that hack deletes my shame
Well, now I know what to avoid if possible 😄
And thank you for pointing me in the right direction!
btw, you said previously
Hey
What is the {% block content %} {% endblock content %} for in django template language?
instead of, erm, trying to tell you how you should redesign your entire project
How would you approach the task?
@ruby palm You use those tags to transfer your html content to another page. Don't remember the name of this method.
extends?
Oh, right
Hmmm, I'm not confident in saying I have one objective right way to do it but I might just serialize the order as JSON and store it in a JSONField (postgres only) -- or just put it into a CharField (any db).
{pizza_id: quantity} -- so like {1: 2, 3: 1} to say 2 of pizza id 1, 1 of pizza id 3. Then just build off that.
So then you just have one object per order, with any complicated listy information being serialized
Thank you!!! @frigid egret
@ruby palm to chime in blocks are cool because it lets you do stuff like...
base.html
{% block head %}
<head>
<title>MySiteName</title>
{% block extra_head %}{% endblock %}
</head>
{% endblock %}
...```
home.html
```html
{% extends 'base.html' %}
{% block head %}
<head>
<title>Ha I overrided the entire head</title>
</head>
{% endblock %}
...```
other.html
```html
{% extends 'base.html' %}
{% block extra_head %}
<script async src="https://HaImJustAddingToTheHeadNotReplacingIt.com/script.js"></script>
{% endblock %}
...
In line 4 of base.html, havent you missed a block before extra_head?
yes, lol, ty
Ohh it makes a lot of sense now
SORRY, ahhh
Thank you so much @prime ridge and @frigid egret !!!
@prime ridge you must be very careful with those things though, you might confuse new people
yw ^_^
Yeah, my bad. I hate when someone's showing me an example and I get caught up trying to understand the logic behind a typo
Im having a hardtime deploying a django app to heroku
I see this in my heroko logs:
ModuleNotFoundError: No module named 'PROJECT_NAME'
My Procfile is:
web: gunicorn PROJECT_NAME.wsgi --log-file -
Can anyone confirm if this is right?
my projects name is "personal_portfolio"
but I wasn't sure if PROJECT_NAME is an env var
what is your project name
personal_portfolio
then do that
I get a module not found error
but let me try again
Now I get this error 2019-07-19T22:55:40.844492+00:00 app[web.1]: File "/app/.heroku/python/bin/gunicorn", line 11, in <module> 2019-07-19T22:55:40.844609+00:00 app[web.1]: sys.exit(run()) 2019-07-19T22:55:40.844613+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 61, in run 2019-07-19T22:55:40.844738+00:00 app[web.1]: WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() 2019-07-19T22:55:40.844743+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/base.py", line 223, in run 2019-07-19T22:55:40.844994+00:00 app[web.1]: super(Application, self).run() 2019-07-19T22:55:40.844997+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/base.py", line 72, in run 2019-07-19T22:55:40.845121+00:00 app[web.1]: Arbiter(self).run() 2019-07-19T22:55:40.845124+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 232, in run 2019-07-19T22:55:40.845276+00:00 app[web.1]: self.halt(reason=inst.reason, exit_status=inst.exit_status) 2019-07-19T22:55:40.845280+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 345, in halt 2019-07-19T22:55:40.845519+00:00 app[web.1]: self.stop() 2019-07-19T22:55:40.845522+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 393, in stop 2019-07-19T22:55:40.845725+00:00 app[web.1]: time.sleep(0.1) 2019-07-19T22:55:40.845728+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 245, in handle_chld 2019-07-19T22:55:40.846156+00:00 app[web.1]: self.reap_workers()
Arent there some help channels? What is this channel for? I know its for help and all but why does it exist if there are other help channels?
topic chat/help channels are for both discussion and subject-specific support while help channels are for general python support
Ohh I understand
quick question: I want my Flask app to access all files in a certain Folder directory on the clients local system. I want to upload all of these files to my web server. How would I achieve this using Flask?
How do I develop the Flask "Select folder" dialog with native file explorer?
How do I vertical align a card in Bootstrap 4?
@cursive cairn Wait, you're wanting to access someone's local file system using a webserver on a remote machine??? Not sure what you're aiming for.
@prime ridge I’ll try to clarify. The server is run locally. I want the user to select a folder on their computer so the local server can analyze files at that folder without moving files (large file volume).
the server runs on the client computer
Everything is run on clients machine
Not necessarily. Just familiar with Flask
And because I’m familiar, I’ve already built a large portion of my program on Flask
Well, I figure you can do one of two things. You could use tkinter for the file selection bit (assuming you want it to just be a terminal and a file selector)
is the flask app using, um
a web interface?
Yes
ohhh
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
Sweet, thanks
So this would be the interface part
you'd just need to figure out how to get flask to accept that input -- interested to see what that'll look like.
I’ll update you - thanks for the help!
np!
Could someone explain to me what exactly is <nav> for?
I don't see any graphic change when I use or not use <nav> tag
What is it exactly for?
Is there any free complete source to learn HTML and CSS?
Havenät used it but check this out https://developer.mozilla.org/en-US/docs/Learn/HTML
MDN is a good resource in general
https://www.w3schools.com/html/default.asp this is where I learned HTML and CSS
@ruby palm not every tag has a visual impact, many of them don't
and they are just to make the code more readable, so you don't have a million divs
they are "semantic" tags
I assume they also help search engines to look for certain tags and grab the contents, like Google does when it shows you a card of something you typed in, but that's speculation, I haven't examined the HTML of any webpage to see if this is true
So those tags are useful for making wrappers?
I don't know what you mean, I'm not really frontend savy
this is just one of the few things I know
The name attribute is used in form posts to identify that fields data
does anyone know how Flask handles generators when streaming with Response(somethingIterable(),mimetype='whatever')? does it automatically "unwrap" anything that recognizes as bytes?
because if something yields an integer or something and I cast it to bytes inside the Response, it works but what it prints is the address of the iterable object
which of course is ugly but I'm just trying to understand how it works
@ruby palm an ID could be used for CSS or JavaScript manipulation easier then an attribute like name. Sometimes you need to interpret data between the form and your API and leveraging the ID with $(‘#<ID>’) makes that easy
How would I load anything from a link like https://services.runescape.com/m=hiscore/index_lite.ws?player=potatoooe
It should return something, but is not readable as json or plaintext
Looks like they are tuples
Delimited by a space
Each element uses a comma delimiter
I.think the ones at the bottom are weird cause those are for clues etc
It's readable as plain text to me (in a browser) so you should just be able to do a get request and simple string parsing
Yeah, it was a csv
I found another wrapper and figured out what they did
Just a csv of rank, level ,exp 🤷
C10K, C100K possible with redis access on python production-ready?
Do you know how to make an image smaller with CSS?
Hi all
I need an advice on managing inlines in Django
I'm working on a dummy pizza store website for practice.
I have orders which contain user data, and then in each order I have a list of pizzas. That's where I use Inline to get pizza objects.
I would like to add anew field to the order list: total price. But first I have to get all pizza prices, multiply them by quantity. Basically, I have to get those values from an inline object and I only know how to display that said inline object.
If there are classes, why do we need ids in HTML and CSS?
As you may know, IDs are unique unlike classes
Meaning only one element may have a certain ID
But it's really a semantic difference. Nothing is stopping you from using classes for everything, even if some of those classes are unique
But that's just bad practice
I believe the difference is in how they are styled by default
spans are displayed inline while divs are blocks
Something like that
so you could use a span if you want to have some inline element in a paragraph of text
Oh, ok!! Thank you, kind sir!
Hey guys im trying to make a website to host my portfolio, I was wondering if you had any suggestions as to where to store my projects to link on the website
it also makes a difference for nesting if you have other elements and are using HTML5 rules, a div can't nest inside a <p> tag, for example, and will automatically close the preceding one
@ruby palm
Mesha. A github profile is usually whats linked to. If you mean hosting them, then a cheap vps is an option
from django.shortcuts import render
# Create your views here.
def home(request):
return render(request, "coffees/home.html", {'title' : 'Home', 'where_css' : 'css/styles.css'})
templates/coffees/base.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
{% if title %}
<title>Coffees - {{title}}</title>
{% else %}
<title>Coffees</title>
{% endif %}
{% if where_css %}
<link rel="stylesheet" href='{{where_css}}'>
{% endif %}
</head>
<body>
{% block content %}
{% endblock content %}
</body>
</html>
templates/coffees/css/styles.css:
h1 {
color: red;
}
templates/coffees/home.html:
{% extends "coffees/base.html" %}
{% block content %}
<h1>Welcome to the home page!</h1>
{% endblock %}
However , "Welcome to the home page!" doesnt become red :(
Why does it happen?
Help, please
I dealt with this problem the whole afternoon and still no solution
I’ve been deploying async web services to Kubernetes for a while now at work and I wrote a summary of what I’ve learned along the way. Thought it might interest y’all... https://link.medium.com/w4CUH9cJxY
just realized this isnt a help channel my b
Jafactor can you use dev tools to see if there is a 404 error for your style sheet?
Hi all
I'm trying to run custom authentication on my website (study project)
So that users only need phone number and password to be able to register and log in
Here's my models.py:
from django.db import models
from django.contrib.auth.models import (
AbstractBaseUser, BaseUserManager
)
class UserManager(BaseUserManager):
def create_user(self, phone, password=None, is_staff=False, is_admin=False, is_active=True):
if not phone:
raise ValueError('User must have a phone number')
if not password:
raise ValueError('User must have a password')
user_obj = self.model(
phone=self.phone
)
user_obj.set_password(password)
user_obj.staff = is_staff
user_obj.admin = is_admin
user_obj.active = is_active
user_obj.save(using=self._db)
return user_obj
def create_staffuser(self, phone, password=None):
user = self.create_user(
phone,
password=password,
is_staff=True,
)
return user
def create_superuser(self, phone, password=None):
user = self.create_user(
phone,
password=password,
is_staff=True,
is_admin=True,
)
return user
class User(AbstractBaseUser):
phone = models.CharField(max_length=100, unique=True)
name = models.CharField(max_length=100)
email = models.EmailField(max_length=100, unique=True)
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
USERNAME_FIELD = 'phone'
REQUIRED_FIELDS = []
objects = UserManager()
def __str__(self):
return self.phone
# def get_full_name(self):
# return self.phone
#
# def get_short_name(self):
# return self.phone
@property
def is_active(self):
return self.active
@property
def is_staff(self):
return self.staff
@property
def is_admin(self):
return self.admin
I also added AUTH_USER_MODEL = 'users.User' to my settings.py
But when I try to register a new superuser (I've wiped my database to avoid conflicts) it gives me this error:
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "E:\Dev\Projects\DjangoPizzaShop\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "E:\Dev\Projects\DjangoPizzaShop\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "E:\Dev\Projects\DjangoPizzaShop\venv\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "E:\Dev\Projects\DjangoPizzaShop\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 61, in execute
return super().execute(*args, **options)
File "E:\Dev\Projects\DjangoPizzaShop\venv\lib\site-packages\django\core\management\base.py", line 364, in execute
output = self.handle(*args, **options)
File "E:\Dev\Projects\DjangoPizzaShop\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 156, in handle
self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
File "E:\Dev\Projects\DjangoPizzaShop\users\models.py", line 37, in create_superuser
is_admin=True,
File "E:\Dev\Projects\DjangoPizzaShop\users\models.py", line 15, in create_user
phone=self.phone
AttributeError: 'UserManager' object has no attribute 'phone'
Can someone help me with that please?
Anyone?..
user_obj = self.model(
phone=self.phone
)
should be
user_obj = self.model(
phone=phone
)
Tried that, same result
@timid arrow Oh wait, I just double checked and now it works. Odd, I must have made some mistake the first time then. Thanks!
@rigid laurel thank you
Anybody here have any experience sending an PIL generated image to your website and displaying it?
I've successfully sent my image and received it but since its in binary I can't just display it.
Might not even be binary though, I have a hard time reading it. Anybody remember how you did it?
how do i differentiate users in flask?
for example, i have a form that saves the data as JSON file
i want to name the json file differently per user, so that when the y try to change it, the server knows which JSON file to change
There is this thing called database
can i use sessions?
Where are you storing user data
server side
i guess i can use sessions
thanks :> i didn't get how sessions work clearly at first since i thought all users access the same dictionary.
sorryy.. i thought if i set the session['user'] when i access the login page from my computer it would replace the session['user'] that was setted when i logged in from my phone
i guess that wasn't the case
i want to differentiate each user
You gonna need a storage on your server
And most common case to deal with that is database
i didn't see the need for a database since it's only a local/LAN webserver.
Yeah but if you save something on a session, that's gonna be available only on one browser session
Only one user
once the browser is closed, the session is gone?
Yes but some data is remembered
i'm going to use the session to differentiate users
I would strongly recommend making a database
then save the json on a folder named using the username stored in session
Databases are quite fast nowdays and easy to setup
i'd consider that too
if i see some inconsistencies with the flow i want to implement
thankss
Session only lives in a browser, not on a server
lemme make some pseudo code
app routing on /login
set session['username'] = form data
app routing on /settings
create json from form data
save on folder named session['user']
Are you gonna use only one device or more
more
What lives in one's session, doesn't live on other's
In this Python Flask Tutorial, we will be learning how to create a database using Flask-SQLAlchemy. SQLAlchemy is a great tool for working with databases bec...
that's actually what i need
but i guess it wouldn't hurt to use a database
so yeah
thanks for convincing me :>
Let me get home aight?
I cant type while on work :p
I'll ping you when i get home
okay :3
hi anyone here?
am working with flask
from SecondTest import func1
from SPEED2 import NetSpeed
import time
import multiprocessing
app = Flask(__name__)
@app.route('/')
def student():
return render_template('input.html')
@app.route('/result', methods=['POST', 'GET'])
def result():
ip1 = request.form['IP1']
sp1 = '8200'
ip2 = request.form['IP2']
sp2 = '8210'
print(ip1)
print(ip2)
speed = multiprocessing.Value('f', 0)
ping = multiprocessing.Value('f', 0)
endFlag = multiprocessing.Value('i', 0)
endFlag.value = 1
manager = multiprocessing.Manager()
shared_list = manager.list()
p1 = multiprocessing.Process(target=NetSpeed, args=(ip1, sp1, speed, ping, endFlag))
p2 = multiprocessing.Process(target=func1, args=(ip2, sp2, speed, ping, endFlag, shared_list))
p1.start()
time.sleep(20)
p2.start()
p1.join()
p2.join()
# print(shared_list)
return render_template("result.html", shared_list=shared_list)
if __name__ == '__main__':
app.run(debug=True)
what the above program does is: get 2 IP address as input, do some process. Process p1 updates its values to Process p2.
Process p2 has access to shared variable named - shared_list, whose value changes every 30sec. I want to display this dynamically changing shared_list in the front end.
<body>
<form action = "/result" method = "POST">
<p>IP address and Port number of device 1 <input type = "text" name = "IP1" /></p>
<p>IP address and Port number of device 2 <input type = "text" name = "IP2" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>
</body>
</html>```
Above input.html takes 2 IP address as input.
- IN SHORT - PROCESS WHICH HAS ACCESS TO SHARED_LIST, KEEPS CHANGING THE VARIABLE'S VALUE'. I MUST DISPLAY THE CHANGES IN FRONT END *
how do i display the changes
you have to either pool the server from the client periodicaly, or use some kind of event to send data at the server intiative.
I dont know how to implement that unfortunately
and thats where i am totally stuck and clueless
Hey. I was using this in CSS but it didn't change anything but it should. Do u know what might be the problem?
p{
font-family: Arial;
}
do you have the Arial font installed?
check the paragraph in the browser inspector tool to see if there are any other CSS rules that might be overriding it.
Hey. I wanted to make an animation. When user would hover on a word "Leaders" it would change from red to green. What might be wrong?
CSS:
Leaders:hover{
animation-name: changing;
animation-duration: 3s;
animation-iteration-count: 1;
}
@keyframes changing {
from {color: #b8b8b8;}
to {color: green;}
}
HTML:
<li class="Leaders"><a href="#"><strong>Leaders</strong></a></li>
@round saddle you're missing the . in front of Leaders in the css
lol
Thanks!
nw
Guys, if I buy domain on sale and registrar shows that renewal price is $9, will it stay same price even after a year?
I mean sale price is 3 and renewal is 9
You pay it for 3, next time it gets the renewal price is 9
@vagrant adder thank you.
hey guys! I made something that manipulates data and calculates a few statistics based on a postcode.
Expected behavior: user inputs a postcode (44400) and an essence type (gazole)
# the correct answer is this ((name, address), (average prices over 12 months)) /thanks @ jojo#2133:
(('E.Leclerc Station Service', '10 Rond-Point de la Corbinerie, Rezé'), [1.348, 1.319, 1.317, 1.352, 1.41, 1.418, 1.395, 1.401, 1.427, 1.475, 1.426, 1.358])
(('E-Leclerc service station in Reze Cedex', '1 rue Ordronneau, Route de Pornic, Rezé'), [1.347, 1.309, 1.321, 1.36, 1.411, 1.416, 1.387, 1.411, 1.432, 1.473, 1.408, 1.329])
(('E.Leclerc Station Service', '10 Rond-Point de la Corbinerie, Rezé'), [1.343, 1.312, 1.311, 1.342, 1.414, 1.412, 1.391, 1.398, 1.427, 1.473, 1.408, 1.354])
The issue here, is that, when I launch my flask server, it does correctly starts and on user input, follows the expected behavior — but only on the first time, when I go back, refresh the page (anything unless I restart the flask server (dev or prod btw)), it appends to the html output in a weird way, and does not reset the content, and display the nth request (see attached)
Flask script gist : https://gist.github.com/ceIia/7780c207c30e51d57ef8b817ad6e4d34 (I only added the flask related files, not the actual scripts, because I tried them directly from the CLI and it was working fine, giving the expected results everytime- which made me suppose it does come from the Flask server somewhere? Tell me if you need anymore information).
Thanks a lot for taking the time to read this, sorry for the wall of text!! 😅
I don't see anything wrong with your flask script, try printing the results from yearly_average_constructor after each request
I suspect something in there is not resetting
it does not get reset?
i think that's because you are constantly writing to a file and between requests it is filled with data from previous requests
can anyone help me out is $element.innerText and $element.href the proper syntax?
I suspect you'll have the problem of it selecting the h3, not the A inside the h3
Hey. I have a small text which is in this class. There is also another one, (Leaders) when someone hovers on it then it should'v cover this text in class About us but even with z-index.
.Leaders:hover{
animation-name: changing;
animation-duration: 2s;
animation-iteration-count: 1;
animation-fill-mode: forwards;
z-index: 5;
}
.About-us{
color: #384e69;
position: fixed;
font-size: 5vw;
left: 38vw;
}
What might be the problem?
The animation works
but the text using class About us covers it
position: Absolute?
what should i be using ? im running out of ideas since nothing seems to work
Z-index only functions on elements that are positioned something other than "static", which is the default
"relative" might be more helpful here
Hmmm... I tried relative and absolute on Leaders class but it still doesn't work.
We'd need to know a bit about the underlying html then
Z-index controls the relative placement of "stacking contexts" in their parent "stacking context"
so, if you've already got a container that doesn't also contain the "about us" but is also positioned nonstatically, then that one must be greater in z-index than the about us label
also note opacity and transforms trigger stacking contexts
Stacking contexts are an aspect of CSS that trips up most developers. I don't think I fully understood them until I wrote the layout chapter of CSS Master. Sure, I understood that z-index required position to be something besides static. But that's about as far as my comprehe...
This is the HTML
<body>
<header>
<img src="https://i.imgur.com/e4IPafW.jpg">
<nav>
<ul>
<li><a href="#"><strong>Join us</strong></a></li>
<li><a href="#"><strong>Rules</strong> (not ready)</a></li>
<li class="Leaders"><a href="#"><strong>Leaders</strong>(not ready)</a></li>
<li><a href="#"><strong>In-game clans</strong>(not ready)</a></li>
<li><a href="#"><strong>Home</strong>(not ready)</a></li>
</ul>
</nav>
</header>
<div>
<h1 class="About-us">About us</h1>
It's part of the whole, but it's part about this
is header position:fixed or sticky?
fixed
right
so you'd need to elevate <header> to be higher than "About-us", since that's the interaction you're seeing
so... I need to add z-index to it?
Yes
z-index is contained within layers, and each layer is created whenever a stacking context is
Ohh... It works now, Thanks!
you can't break out of a z-index layer with z-index, so since <header> creates a new context that is below About-us's context, it doesn't matter what value that your leaders gets, since its flattened down into the one that <header> uses when it's compared to anything outside of <header>
I have a question. Is this possible? I'd like to make an image transparent when I would hover on a text which is somewhere else (on the same website ofc)
Depends on your constraints
If the image is next to or inside the hovered element, you can do it with css, via the adjacent sibling combinators and similar.
if it is not, then you can use javascript
<container>
<item1>
<hoveredelement>
<elementinside></elementinside>
</hoveredelement>
<adjacentelement></adjacentlement>
</item1>
<untargetableelement></untargetablelement>
</container>
Hello. Im working on Django app and i have one problem. Why i dont see tabulr and stacked admin in django admin?
I don't think you registered your ItemAdmin class to the Item model
@native root : (message from 11:13am) yearly_average_constructor outputs the wrong behavior, so it actually might not be flask you're right, @vagrant adder. The thing is, I have in every python script called by the main Flask script, a variable_name = [] (or 0) at the start to make sure it starts clean everytime...
(I updated the gist to add the file from which it constructs the wrong list, if you maybe have an idea of what could be wrong)
https://gist.github.com/ceIia/7780c207c30e51d57ef8b817ad6e4d34#file-create_year_data-py
@native root 😄 fak! i spend 2h 😄
pump_list and raw_array should be inside the function
unless you wish to keep the sticky behavior for some other module, at which point you can write a reset() function that reinitalizes them. If you do that, make sure to use global
ahhh, my bad then
You got your problem solved? @smoky swan
Cheers mate @smoky swan
hey! it's me again 😅
found this great tutorial online about chart.js and flask -> https://blog.ruanbekker.com/blog/2017/12/14/graphing-pretty-charts-with-python-flask-and-chartjs/
here's my issue: I have a list of gas stations with different datasets everytime (as shown on the screenshot): what would be the workaround to reset the js script datasets to generate a new graph everytime?
also, at the end, i'll be supposed to generate a big graph with every line stacked, which is done by giving every dataset at once to chart.js, and even that is another whole thing.
what would be the best workaround this? should I have multiple instances of the js script running for each graph? (chart.js docs : https://chartjs.org/docs/latest/)
(sorry again for the 2nd wall of text today- thanks so much for the help you guys gave me: i've progressed so much in python over the last two weeks thanks to your help)
I am a big sucker for Charts and Graphs, and today I found one awesome library called Chart.js, which we will use with Python Flask Web Framework, …
you simply make a function
that has input params the parameters of the graph
and renders the graph for the specified input
if for example you're scraping data, and a user inputs a link for a specified petrol station
you simply fetch the data, and return it, and then write a js function to handle the data with the specified input
and that's that
make a request to the database and collect the data.
After that shape data in any way or form you need and just pass it as argument in chart.js Chart object
chart.js updates realtime
Hello
Well this is embarrasing
Im gonna to ask a question I already asked in this channel, two weeks ago
Because I forgot what the answer is and as I'm a dumbass I didn't save it into any archives
Is there a free source for learning data structure fundamentals and/or pattern designs?
FYI you can search pretty nicely, there'sa bar in the top right
from: jafactor in:web-development
@vagrant adder @flint breach yeah- but that would not work if I have to display multiple graphs at once
Why not
Why
Make multiple requests
On my internship i had to graph jenkins tests and i used mutiple charts at once
exactly
I think I'm not following on the last part- I would have as many copies of the js script in my html page as I have graphs rendered?
Yeah
Although, you can make 2 instances of Chart object in a single js script
But i'd recommend separating each instance im separate scripts
hmmm- i hope it doesn't affect performance too much
v8 bejbi
@flint breach where you from
Slo, why
How do I disable the jQuery UI sortable's windows auto resizing?
Ok, thanks @native root !!
would django be better for a larger scale api than using something like flask or quart?
How do I turn on debugging in Flask using Powershell? I have tried $env:FLASK_ENV="development" but then I get an error No module named C:\Users\shado\python-scripts\microblog\venv\Scripts\flask
that doesn't do anything
$env:FLASK_ENV="development" is how to set the variable in Powershell
it's not set because I've already been down that road
$env actually changes the mode but set does not
It worked for me
it doesn't for me
I can turn debug mode on I just can't get the app to run
and flask is already installed
I can run the application outside of debug mode
didn't do anything
no I'm using a tutorial, but the tutorial code is on github
I have gitbash but I don't know how to use it
in gitbash?
can I use gitbash as an interpreter?
export gives an error in Powershell
I have no idea how to get this set up in gitbash
is git copying my Powershell directory?
vsc?
when I do export it doesn't do anything
Export in bash sets env vars
I don't understand what you're asking because I don't know how to set directories or run the program from git
if I don't have my environment activated in Git how can I work with the variables?
activate env by typing source venv/Scripts/activate
Okay you have got to start at the beginning here
I don't even know how to set directories in Git Bash
What do you mean by setting directories
Setting the directory for my Flask application
if I just start setting variables outside of the app it's not going to do anything
I don't know how to use git bash at all so this is really confusing to me
I figured that part out but now I'm stuck trying to get it to run without debug
alright @vagrant adder I got everything working in git bash then set export FLASK_DEBUG=1 and got the same issue
How do I do that?
I also realized during this that the guy who made the tutorial has been using git bash for his examples
@vagrant adder
Do you know how I get get debug turned off before I try that?
I used export and now it's permanently set to on
setting app.debug to true in the init.py didn't do anything @vagrant adder
debug turn off?
I just restarted git bash
export FLASK_ENV='production'
yeah I tried that and it stayed on
I need it on though
Did you not read my original question?
I'm having trouble because I can't get debug to work in Powershell
and now we've determined it also does not work in Git Bash
and gives me the same problem
Regardless I'm having the SAME ISSUE in git bash
@vagrant adder don't use the r-word on this server please
What tutorial are you following
The Flask-Mega-Tutorial by Miguel Grinberg
a lot of files
I'm running the script using flask run
it works when debugging is off
yes
yes
of my config.py?
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'app.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False```
Under sqlalchemy_track_modifications put this line:
DEBUG = True
And if you need it off, change to False
That didn't effect anything when I run flask
Is your script working fine?
the program works absolutely fine when debug is off
it's a blog app, I can go through the different pages and login and out
Try running with debug off
what I'm saying is setting that variable in the config didn't change anything
debug remained off
I can turn debug on from git using export FLASK_DEBUG=1
and turn it off setting it equal to zero
but I can't get the app to run when it's on
Okay, it isn't working through cli
Let's try it through code
If you really want to deal with env vars in powershell, head to #491524019825278977
It doesn't matter because that' snot the issue anymore
it doesn't work in Powershell or Git Bash
I can get debug turned on but the application simply won't run
k I'll get at it
thanks for all of the help even though the problem isn't solved yet
👍
It still doesn't work, I've tried all of these and have the same issue
I've set FLASK_ENV=development
and FLASK_DEBUG=True
and still nothing, same problem as the original question
Although, i always use code version
Ah
Wadup chapo
so I have tried downgrading Flask and run into the same issue
tried it in command prompt as well
@native tide Werkzeug 0.15.5 introduced an issue for windows users that sounds like what your experiencing
Try downgrading Werkzeug to 015.4
Or run with python -m flask run to bypass
@lime thicket That works! Thank you!
Can you explain what's going on or have a resource that can explain it?
Here is a link to the issue on Werkzeug https://github.com/pallets/werkzeug/issues/1614 the short and sweet is that the reloader used during debug mode attempts to rebuild the args used to execute the code initially and fails to do it correctly
A lot of back and forth occurred as the issue only happens if you install flask a certain way so it was hard to pinpoint
Found the code that contained the reloader string via some googling (Werkzeug) and then noticed they had shipped a new release a few hours prior. Started digging into the code to see if the release changed the reloader and it did
Neat, I'll have to keep that in mind to check out different packages for errors when I search.
Does anyone know how to ping a redis server hosted on heroku?
locally i can just do:
r = redis.Redis(host="127.0.0.1", socket_connect_timeout=1)
r.ping()
but REDIS_URL when using heroku is something like redis://h:839453h94h3fh@ec2-34-25-15-236.compute-1.amazonaws.com:16969
and i'm not sure exactly what to use with the host argument
All I really want is a way to check if redis is currently running
I think you can use that env var as a host argument
I have a little sortable list made with jQuery UI.
How I can disable the auto resize of the window when I drag a element of the list out of the borders?
The reason it's expanding is because the sortable ui moves the element according to position: absolute
when elements move outside their containers, and there's no other properties specified, css's overflow property defaults to scroll
which causes the scrollbar to appear and the element to continue to expand
if you wish the content to be cut off, you can set overflow to hidden
Anyone here ever worked with DJango and Angular?
@vagrant adder just to update what I was asking about before: you can just use the env var if you use redis.from_url() instead of 'redis.Redis()'
So you need actual adress to ping a redis server?
.ellipsis-anim span {
opacity: 0;
-webkit-animation: ellipsis-dot 1s infinite;
animation: ellipsis-dot 1s infinite;
}
.ellipsis-anim span:nth-child(1) {
-webkit-animation-delay: 0.0s;
animation-delay: 0.0s;
}
.ellipsis-anim span:nth-child(2) {
-webkit-animation-delay: 0.2s;
animation-delay: 0.2s;
}
.ellipsis-anim span:nth-child(3) {
-webkit-animation-delay: 0.4s;
animation-delay: 0.4s;
}
@-webkit-keyframes ellipsis-dot {
0% { opacity: 0; }
50% { opacity: 1; -ms-transform: scale(20); /* IE 9 */; -webkit-transform: scale(20); /* Safari */; transform: scale(20); }
100% { opacity: 0; }
}
@keyframes ellipsis-dot {
0% { opacity: 0; }
50% { opacity: 1; -ms-transform: scale(20); /* IE 9 */; -webkit-transform: scale(20); /* Safari */; transform: scale(20); }
100% { opacity: 0; }
}```
```html
<html>
<link rel="stylesheet" type="text/css" href="css.css">
<body>
<h1>
Loading<span class="ellipsis-anim"><span>.</span><span>.</span><span>.</span></span>
</h1>
<h1>
<span class="ellipsis-anim"><span>.</span><span>.</span><span>.</span></span>
</h1>
</body>
</html>```
How can I resize the ellipsis at 50% through the animation ?
I tried scale 1.5 but it didnt work (so i put a huge value just to make sure)
I don't see anything in that code that would prevent transform:scale() from functioning
...cut, the issue is that transform:scale does not apply to non-block elements
which span is
See here
Just looking for a bit of direction not a full blown answer as I assume this isn't a quick question.
I'd like to have a table on my website. This table will pull data from a database. When the database updates I'd like the website to update only the values that have changed in the database automatically. I'd like to do this as efficiently as possible, is python the way to go or is this a problem that will likely be solved by JS/JQuery/Ajax or something ?
I have a sortable list by jQuery UI:
<div id="draggable-cards">
<ul>
<li id="item1">Item 1</li>
<li id="item2">Item 2</li>
</ul>
</div
$(function(){
$('#draggable-cards').sortable();
});
How I can save the order of the list and read it with flask?
@woven surge without reloading the page and having the templating engine handle the changes to the table you will need some sort of JavaScript to fetch updates from an API and then modify the dom
so the JS needs to keep checking if there has been an update
@tough star you could grab the list of <li>s and post it back to flask via an endpoint. With jquery it could be something like $( "li" ).toArray() to gather the list in the order it is
or can JS listen and then when the DB updates it can send a signal
Yes unless your okay with the whole page reloading, and if so you can just use the templating engine
that way it doesn't need to keep querying the DB
JS can’t listen, you could do some sort of socket setup possibly with the database update triggering an event but that increase the complexity significantly
@lime thicket Can I use a sort of ajax?
Yeah to send the data back to flask you would likely do some sort of Ajax POST or PUT
@lime thicket But I don't know how to do
The jquery documentation has some nice examples if you scroll towards the bottom https://api.jquery.com/jquery.ajax/#jQuery-ajax-url-settings. Try to start small, get a simple post to work that prints some string on the server side, then try and post the list order, then post the list order and save it however you need to
The flask mega tutorial also covers Ajax in one of the later sections https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xiv-ajax
been following a django tutorial and my redirect function is returning a null value
!ask
Asking good questions will yield a much higher chance of a quick response:
• Don't ask to ask your question, just go ahead and tell us your problem.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving
• Keep your patience while we're helping you.
You can find a much more detailed explanation on our website.
from django.shortcuts import render
from django.shortcuts import redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
messages.success(request, f'Account created for {username}!')
return redirect('blog-home')
else:
form = UserCreationForm()
return render(request, 'users/register.html', {'form': form})
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name ='blog-home'),
path('about/', views.about, name ='blog-about'),
]
this is where 'blog-home' is in
when I do submit the form I get an error saying the returned value was null
ping me with answer if anyone does help, im ganna sleep
I have a question , how do I prevent the user to click the browser back button after moving to another page
I have tried window.location.replace and it doesn’t work
There's a web history API they may be able to do that
No one has a clue on my issue?
I think you have to remove your form from inheritence from conditional statement
I am trying to set my django website in prodution with heroku, but if I change debug mode to False the website doesn't work and it gives me an Server Error (500) If debug mode is on True the website does work completely.
So I have a webapp with a frontend and a seperate backend with an api. Regerstering works fine but how could I start a user session with my api?
Like I have a user log in and the frontend sends the login info to the api
Then it starts a user session
How would I make that work in flask? Would I have to implament oauth and all that rigamaroll like how discord does it with it's api (bots, clients)
Jwt is almost deprecated rn
You are better off managing your sesssions completely on frontend
What frontend are you using?
What's the use for python3 manage.py makemigrations?
Preapares changes of your models
It commits changes to django folder
Prepares webserver for running with new changes pretty much
How I can make a google login using Authlib?
Authlib?
I try to avoid it whenever i can
I use other 3rd parties oauth plugins/modules since those actually have more recent code
@vagrant adder I want to use it with flask. I used the Flask-Oauth "plugin" but in the docs it says to use authlib.
does anyone mind going over how to tie reactjs frontend to a flask backend on a high-level? i have a react repo with create-react-app but how can i connect that to flask that's running separately?
Generally you design the flask app as a rest api that communicates with json data. Then you call the flask endpoints using ajax requests in react. But the main thing is to design your flask side as a rest api which you can find a lot of resources online for
so i've been reading that's one way to do it. where the flask api is consumed by the react frontend. but is there also another way to do it where I can just run the flask app and have it serve up react without running a separate react instance?
You could have a single view that includes a script tag of your react app
On the same app that the react is consuming
You might need babel js or Web pack or something to compile to the pure js. I'm not 100%
I am trying to set my django website in prodution with heroku, but if I change debug mode to False the website doesn't work and it gives me an Server Error (500) If debug mode is on True the website does work completely.
@hushed burrow you'll have to break down create-react-app's default config and set it to compile all the code in the directory of your flask app. Don't know if an api would be a viable option here
anyone here able to answer a question about django? ))
@vagrant adder The last version was released on 2014...
It say to use this: https://github.com/marksteve/flask-oauth2-login
But this is also very old
jsut curious in django you do a createuser thing ot create a user but what if you extended from the user class and created ur own sorta user, is there any way to create a user from teh command line again after that?
@zealous igloo Yes, if you make custom classes from django built in classes and your program is going to treat them as though they are built in classes.
oh okay so then i can createsuperuser and stuff and it would create that sorta user and would it change my token authentication process at all?
I've actually just finished doing such thing on my training project, put phone field in place of username
It wouldn't if you do it correctly. What you have to do is go to library files, find the class that you need, copy-paste it into your models.py and make changes you want there.
Here's my example if that helps:
...how do I use code paste thing? Keep forgetting
nvm, I'll just send you the file. What I did there is I copied library classes that I need and made my custom changes to them. So now django treats my custom classes as though they are library.
Is there a load limit on flask
Its not accepting more than 4000 request per min
Any way to use multiple cores or just anything so that it accepts more request per second
dang okay thanks a lot @frigid egret this looks rela tough so i can't understand it at the moment but i'll defintiely use htis and waht u said as reference as i go thru it. Tanks for shwoing me the file it's really ehlpful
This is just a training project? did u just get into django or something?
@zealous igloo Been studying it for last few months. I've also got a mentor that's helping me.
oh wow jsut a few motnhs dang, i haven't studeid it for a few motnhs yet but im sure i won't be close to where ur at
Nah, trust me, this was an easy thing to do. Just wait till you get to making something that django wasn't designed for, that's where real tough part starts XD
by the way i was kind of thinking about it and wanted to get ur opinion on if i really need to change the default user class. So like i have a program where the user can write a list of stories they have read and i was thinking i was supposed to extend the user model to include stories read but instead could i just use the default user model and on the front end it can request for the data of the user by sending a get request with it's primary key and the database just finds whatever info is associated with that primary key and sends it
ommmggggg scarrrrryyyyyyyyyy
I mean as long as there are tutorials (and there are plenty on user handling) it's relatively easy. Once you get into territory where there are no articles or any information, it gets real tough
this is my first time using django for a site so yeah just like being able to develop these client-server applciations(i think that's waht it called when frontend and backend compeltely seperate) and it been tripping me up
ohh yeah for sure that must require insane thinking
So yea, start with tutorials and that'll give you general understanding of what django is capable of.
oh okay yeah thanks i'll be sure to
yw
Is there a load limit on flask
Its not accepting more than 4000 request per min
Any way to use multiple cores or just anything so that it accepts more request per second
or is it a server issue ?
axios.get('http://127.0.0.1:8000/api/info/', {'authorization': 'Token' + this.props.token})
im using react wtih django rest frameowrk and i am trying to use the token I get from succesfuly logging in and just curious how do i perform requests now with axios adn teh token? in Postman I go to Headers and type Authorization as the key and the value is Token (some arbitrary token), so i'm guessing i would have to do an equivalent of that with axios, how would i go about that?
@gleaming herald flask can only serve one request at a time, see its deploy documentation to get around that
@zealous igloo Try capitalizing "Authorization: and making sure there's a space between "Token" and the token
I tried the authorization capitalizing and with teh token i added space and i console logged it to confirm the value and yeah it does get the token but it still doesnt work, do i somehow have to include the word "Headers" in there cuz iwth Postman Iput the info in body but the token goes in palce called headers
@native root I have my own server
with 8 cores
but python is using only one
and during load testing it shows that 4K is the limit
@zealous igloo see here, https://stackoverflow.com/questions/44617825/passing-headers-with-axios-post-request-reactjs
Vraj, are you using flask's dev server, or a wsgi frontend?
omg thanks @native root this helped so mcuh
Someone able to tell me why this is rendering wrong?
jinja2 template:
<a href="{{ link.1 }}"
title="{% if link.2 %}{{ link.2 }}{% else %}external link{% endif %}"
{% if link.3 %}id="{{ link.3 }}"{% endif %}
{% if link.4 %}target="_blank"{% endif %}>{{ link.0 }}</a>
input is a 5-element tuple of strings
...
maybe its not 5 elements
sigh
still unhappy that the if-else isn't functioning, it's rendering an empty string, which, as far as I can tell, shouldn't be possible?
output:
<a href="/about-us" title="">About Us</a>
Can you send a screenshot of the code instead of pasting it here? Because it looks weird
I would, if this were A) dynamic, B) not manually passed in ;-;
It's pulled from a config file, and not always intended to be internal
gives the code on the page a glare Change nothing, suddenly its working?
Was a stale render showing on live
i tried doing request and request.data but it says request is not defined
new to web dev
idea
is there a way to have a folder with a bunch of markdown files.
And that folder is named like blog or smth
and so when you go to mywebsite.com/blog/subpage it displays the markdown file with the name subpage.md inside of the blog folder.
I think you could have some kind of python parser file but I am not sure.
Essentially I want to be able to create markdown files, directly into the folder, upload it, and boom, html page created.
Another functionality I would like to have is someway to extract variables stored inside of the markdown files, such as:
subpage.md:
[blogpage-name]: My Blogpage Name
I don't remember if that's how you create vars but point remains
@native tide django or flask?
Hey all. I'm using Bulma sass with Flask and something, somewhere is breaking my hamburger menu
sass_bundle = Bundle(
'custom.sass',
filters= 'libsass, cssmin',
depends= ('sass/**/*.sass'),
output= 'css/bundle.css'
)
In my app.py file
@charset "utf-8"
@import "sass/custom/my-colours" // Set custom colours for site
// Import Bulma
@import "sass/utilities/_all"
@import "sass/base/_all"
@import "sass/elements/_all"
@import "sass/form/_all"
@import "sass/components/_all"
@import "sass/grid/_all"
@import "sass/layout/_all"
// Custom sass elements
@import "sass/custom/fixed-footer"
@import "sass/custom/logo-img"
@import "sass/custom/tabbed-content"
@import "sass/custom/index"
is my custom.sass file
I've tried removing all of my customizations from the custom.sass file and rebundling the css file and still nothing
I've found the 3rd span in the burger div is broken, but cannot for the life of me find the culprit
Well, the issue is that there isn't a space around that + operator
why, well, depends on where it comes from in the code
Okay let me try removing the cssmin filter
... that was it
lmao
Thank you!
Is there a way I can avoid that when the site is ready for production?
does css minification really even matter?
@native root do you still have your IDE open
I mean I never close them, why?
import timeit
import itertools
import string
def run():
def chunks(products, chunksize):
itertools_chain = itertools.chain
itertools_islice = itertools.islice
for startz in products:
yield itertools_chain([startz], itertools_islice(products, chunksize - 1))
alphabet = string.digits + string.ascii_letters
products = itertools.product(alphabet, repeat=4)
chunksize = 10000
with open("test.txt", "w+") as outfile:
_write = outfile.write
# _join = ', '.join
inner_join = ''.join
for chunk in chunks(products, chunksize):
_write(inner_join(inner_join(c) for c in chunk))
run_time = timeit.Timer(run).timeit(1)
print(f"Done in {run_time:2f}s")```
how long does this take for you
...interesting optimization
it takes 4s for me
on a blue moon it runs at 3.8s but meh
I'll see what else I can do before I toss it into cython
it's a known thing to look up functions even built in beforehand and store in local variables, known to have greater performance but it's a rare thing
and I think I posted in the wrong channel, rip me
@balmy forge
This is web dev channel my dude
Sorry, it was a continuation of another channel, I somehow opened this. My bad
I get this error when I open a flask page:
File "C:\Users\Matteo's PC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\sessions.py", line 375, in save_session
val = self.get_signing_serializer(app).dumps(dict(session))
File "C:\Users\Matteo's PC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\itsdangerous\serializer.py", line 166, in dumps
payload = want_bytes(self.dump_payload(obj))
File "C:\Users\Matteo's PC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\itsdangerous\url_safe.py", line 42, in dump_payload
json = super(URLSafeSerializerMixin, self).dump_payload(obj)
File "C:\Users\Matteo's PC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\itsdangerous\serializer.py", line 133, in dump_payload
return want_bytes(self.serializer.dumps(obj, **self.serializer_kwargs))
File "C:\Users\Matteo's PC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\json\tag.py", line 296, in dumps
return dumps(self.tag(value), separators=(',', ':'))
File "C:\Users\Matteo's PC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\json\__init__.py", line 179, in dumps
rv = _json.dumps(obj, **kwargs)
File "C:\Users\Matteo's PC\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "C:\Users\Matteo's PC\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\Matteo's PC\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
TypeError: '<' not supported between instances of 'str' and 'NoneType'
The full traceback: https://paste.pydis.com/xawevegibo.py
What's your flask code?
There's something going wrong internally there, but maybe I can figure out what's triggering it
@native root This is my flask code: https://paste.pydis.com/aworegovud.py
I'm not sure, but a few things stand out to me
First of which is maybe one of your JSON files is failing to load
the other is that check_user can return None
https://github.com/pallets/flask/issues/2956 Seems to suggest its to do with a JSONEncoder
What is name button's attribute for in HTML?
Perhaps it's being triggered by trying to serialize an openauth state?
@native root I don't know 😦
What is name button's attribute for in HTML?
For example:
<input type="password" name="password">
@river obsidian thank you very much!!!
background-position: 50% 0;
What does it do? It looks like it centers the background image
(It's CSS)
50% is the middle, yeah
background-position: center;
you could also use this, much cleaner
@ruby palm
I don't think so
yours only centers the x axis
but raizo's would center both I believe
well background-position: center; would be 50%,50% i just figured
so well the middle of the screen
the second argument was 0 though
Is there a modern alternative to JWT? Seems like the difficulty in revoking access tokens is kind of a big deal, and it seems like an issue that something else would solve
Flask login
How would you generally go about logging incoming requests that may contain sensitive information such as passwords? I've been considering if it's worth encrypting the sensitive data just for this purpose, or if I should create a logging module that selectively filters sensitive data from the log entries or something.
for me I just hash the password then send the hash away
storing password is storing hash instead of actual password
That isn't going to work in my case, because I need to send the password on to one of multiple third-party APIs.
I guess then the only way is to do a 2-way hash method to hash sensitive data
and only convert it back in case you need it, but that's just as good as logging the sensitive data itself
I mean, I will have access to the plaintext password in the code in any case, it's just about protecting it from someone reading the log.
So I could selectively remove it from the log, which is the second option I thought of.
Just trying to get a second opinion. Maybe there are industry standards for this kind of thing.
I guess normally you would know the hashing scheme of the database storing the password.
So you could just hash it in the client.
normally, yeah, hash instead to keep "evidence" which helps tremendously in debugging and tracing as well
Hrm, yeah, my situation is a bit awkward in that regard.
@open forum, don't log sensitive information. That is a security weak point ! On the other side, even the big one do it... https://krebsonsecurity.com/2019/03/facebook-stored-hundreds-of-millions-of-user-passwords-in-plain-text-for-years/ https://www.zdnet.com/article/github-says-bug-exposed-account-passwords/ https://blog.twitter.com/en_in/topics/company/2018/keeping-your-account-secure.html
@stray nexus I know I shouldn't, I was just asking about the best way to avoid it.
well, to not log the password anywhere is the best way imho. strip it from your log if you want to keep a log of all succesfull/failed login
what is the usefulness of having passwords, hashed or not, in the log anyway ?
Thank you very much, @proper hinge and @mint canyon !!!!
@proper hinge right, thats why i said that
With
background-position: center;
Does Y equal to 0 by default in that case?
So is it the same to write
background-position: center 0;
```?
No, background-position: center; is the same as center center
@open forum Is it possible to use some form of federated login across the services? That would provide a more cerntralised setup at least (think Oauth and other possible options)
@leaden vessel I have no control over the third party APIs, and the credentials passed around are those of end-users of our customers.
We are merely facilitating communication between our customers and these APIs.
@stray nexus I have no specific need to log passwords, I was just wondering whether it's better to strip the logs or to encrypt the sensitive data.
I guess it's generally better not to send any sensitive information in plain text, even if it is over https.
Though I can't think of any obvious way to exploit it.
@native root Ok, thank you!!
ul ul {
list-style-type: circle;
}
ul > ul {
list-style-type: circle;
}
Are those CSS codes the same?
Or does it make a difference to put a >?
‘>’ indicates that the elements must be immediate descendants
Can someone help me please
I'm building a Python Flask contact page
for some reason my contact form want allow me to put input in 🙈
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired, Email
class ContactForm(FlaskForm):
name = StringField('Name')
email = StringField('Email', validators=[DataRequired()])
subject = StringField('Subject')
message = StringField('Message',validators=[DataRequired])
submit = SubmitField('Submit')```
{% block title %} Contact {% endblock %}
{% block head %}
<link href="{{ url_for('static', filename='css/contact.css') }}" rel="stylesheet" type="text/css">
{% endblock %}
{% block content %}
<div class="container contactustext">
<h1>GET IN CONTACT</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Impedit voluptates minima cum odit eligendi, ut fuga suscipit dicta harum repellat assumenda dignissimos! Ad consequuntur ipsam deleniti quidem, quos obcaecati alias.</p>
</div>
<div class="container">
<div class="content-section">
<form method="POST" action="">
{{ form.hidden_tag() }}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Contact Us</legend>
<div class="form-group">
{{ form.name.label(class="form-control-label") }}
</div>
<div class="form-group">
{{ form.email.label(class="form-control-label") }}
</div>
<div class="form-group">
{{ form.subject.label(class="form-control-label") }}
</div>
<div class="form-group">
{{ form.message.label(class="form-control-label") }}
</div>
</fieldset>
<div class="form-group">
{{ form.submit(class="btn btn-outline-info") }}
</div>
</form>
</div>
</div>
{% endblock %} ```
def contact():
form = ContactForm()
return render_template("contact.html", title='contact', form=form) ```
Thank you , @native root !!
Having some trouble sending an email from a script using Flask-Mail
getting the error smtplib.SMTPServerDisconnected: please run connect() first
I'm attempting to use gmail and send an email to another gmail account
mail server is set to smtp.googlemail.com, port 587, TLS is on
does anyone know how to return a json object to a template? returning a JsonResponse(data) does not give me the option to render it to a template
Is anyone familiar with Flask SQLAlchemy?
@humble portal wdym by return it to a template? do you mean pass it to a template? then just jsonify it and pass it as a variable to the render function, use flask.json.dumps (its exactly like json.dumps but is context aware)
Hi
See that blue nav bar?
I want that blue nav bar's width to occupy 100% of the web page
But I can't figure out how to do it :(
Help!!
* {
padding: 0px;
margin: 0px;
}
body {
background: #e6e6e6;
}
.main, header, footer {
margin: 20px auto;
width: 80%;
}
.main {
clear: both;
}
header nav ul {
list-style: none;
}
header nav ul li {
float: left;
background: #66b3ff;
}
header nav ul li a {
display: block;
padding: 10px 20px;
}
That's the CSS code
Have you tried
body, html {
width: 100%;
}
Hey there I wrote a post on deploying django web applications using docker
I hope this helps someone in here ♥
https://lewiskori.com/post/deploying-a-python-django-application-using-docker
Value error :couldnot convert string to float how can i solve that?????
Well how do you convert “abc” to number, what’ll be the expected result
You can wrap it into a try except ValueError as well
@native tide smtp.gmail.com
@iron sinew
Its a lot easier to write apis in flask
@tranquil steeple i'm pretty familiar, just ask the question
@humble portal what framework are you using
@vagrant adder Thanks. I'll try to find some tutorials for that
Corey schafer has a great flask walkthrough
anyone work with amazon mws api
just curious with django i had this sorta website idea and im kinda wondering if it even possible in django. so just in very brief summary i have a site sort of like a excel for tv shows it has columns like wha tyou would rate teh show, how much u liked it outta 10 etc so i have models for the table for each column
would it be possible to make it so each user can customize their tables by adding/deleting their own columns but then im assuming this would mean that for every single user that changes their table from teh default there would have to be a diff model for every single one.
is that doable in django?
@zealous igloo yes
It is doable in django, although you what you are talking about is much more then django itself.
Is it doable in <ANY BACKEND WEB FRAMEWORK EVER> ?
Also yes
oh am i right that every user would have to have their own model for the table
Depends on what you are referring to as 'model'.
im just trying to conecptualize how i would do this, having a really hard time planning it out
u know like model with the datefields integerfields charfields etc
In that case - probably no. All users will have a single table/model, but there will be a field in it specifying which user each record belongs to.
@zealous igloo well, the “user-defined models“ would not be Django models in that case, they will probably have their own representation, this is usually done using NoSQL data storage
Django ORM is supposed to be used with relational databases.
would i have to use a non relational/NoSQL thing database?
@candid basalt well, there is PostgreSQL's JSONField allowing to do some cool schemaless stuff when needed
There is, but it also produces a lot of issues. =]
@zealous igloo as you wish
@candid basalt well, issues would happen too using other databases 🤔
@zealous igloo everything depends on what you want. It's possible to do with either relational or document-based or any other database of your choice. Each approach has it's own pros and cons.
i see wait so hwo could i do this without giving a table a model?
@unborn terrace depends on the use case. When you work with the data structure that needs to be consistent and maintain it's integrity - most of the time you will want relational DB. When you want a lot of horizontal scaling - nosql may be a better choice.
@candid basalt sure, but it does seem appropriate here, where users should benefit from a kind of custom-defined database
Well, the app may also use “real” databases to represent them, but this involves so much more work than most apps of that kind store these user-define DBs in NoSQL storage
Yes, that's true. NoSQL DBs tend to be better for prototyping.
Yet Django has a lot of stuff automated for you, such as schema generation and migrations, to name a few.
@zealous igloo if you want to use Django ORM - you will have to design your data structure around the relational DB paradigm and will have to use Django models. If you want to use something else like MongoDB or similar tech - it may make sense to use it directly instead without involving Django ORM.
Sure but these are not made for user-defined databases, they are for the app developer
oh okaya nd if i do use DJango ORM would i create a new Model for every singel user who wishes to have a differnet table?
if i useed a nosql database would mongodb be best choice for that?
do use DJango ORM would i create a new Model for every singel user who wishes to have a differnet table
@zealous igloo no, that's what I am just saying
i see it just @candid basalt said i would have to use DJango Models i just don't get how i would have ot use it and not have to create a new model for every single user
i saw your solution about how they would have a unique datbase representation but taht is just for nosql
That's the thing, these apps usually implement their own kind of “ORM” to manage that
oh so it might be more of a hassle to use djangos?
Very usually leveraging flexible schema-less datastores
No more than something else
i see it jsut so how would i use Django models for this?
There are few ways to handle this:
- Make a predefined set of additioanl fields users can choose from. This way you can still get away with clean RDB structure.
- Make use of JSONField to store custom user columns (may have issues later down the road with querying them).
- Use non-relational DBs such as MongoDB to store all your data (may have issues with attaching that with regular Django user management etc, which generally wants RDS under the hood).
- Not use Django at all and go with flask+mongodb+something else (will loose Django's "batteries included" functionality).
You don't, your Django models will be used to model your application entities, not for the users to define them themselves
If I were to do this - I'd try JSONField approach first. It seems the most convenient and less intrusive if you want to keep using Django/PostgreSQL.
^
oh wow okay thanks for the option idk whta jsonfield is atm but i'll look into it rn and i'll keep those other ways in mind for sure
Credits go to @unborn terrace for that one. =]

thanks you both provided a ton of helpful info
if i understand something wrong or if you guys have anything to add, please let me know
I have done an overview concerning webframeworks, please comment or correct me, if i understand something wrong.
does mod_wsgi work for python 3.7 (windows)?
Yes
@dim axle
Forgot about nosql databases and servers such as wsgi/uwsgi and gunicorn
But that's about it
Asp.net is also good backend (c#)
PixiJS 5.1.0 - ✰ WebGL ✰ http://www.pixijs.com/ ♥♥♥
Do you have those characters in a console after calling the function PIXI.utils.sayHello()?
I never got an answer in #databases, but is there any reason to run/store/write db create scripts as python code, rather than just running them on the db directly via sql?
With Flask Blueprints, how would I assign a wildcard route? Like if I want /foo/bar/* to route to a particular function (or Flask_Restful resource)?
What do you mean by wildcard route
Like, I want /foo/bar/<arbitrary name here> to route to a particular function/Resource, and have access to whatever string was specified in <arbitrary name here>
Basically, I'm going to do some customizable database models, and I need for the REST API to be able to serve the arbitrary models/fields
https://flask.palletsprojects.com/en/1.0.x/quickstart/#variable-rules I believe is what you want
Ahh, perfect! Didn't realize Piers Morgan was a Flask expert!
Gotta find something to do when there are no sausage rolls to rant about
@app.route('/<int:wildcard_hete>')
def saki(wildcard_here):
return wildcard_here```
@plucky fiber
Thanks!
I think only supported types are int and str
@vagrant adder thank you!
Mon Aug 5 04:39:13 2019 - SIGPIPE: writing to a closed pipe/socket/fd (probably the client disconnected) on request
i randomly get this in my logs on a nginx/uwsgi/flask setup. anyone can shed some light on what i should be checking ?
While lightweight and easy to use, Flask’s built-in server is not suitable for production as it doesn’t scale well and by default serves only one request at a time.
Any alternative
or ideas how to make it production ready ?
there are many other scalable alternatives - django is popular, so is tornado
sanic is also a great alternative to flask as well
@balmy forge Sanic sounds promising
There's a thing called waitress to make flask fast I guess
is it possible to still use rest frameowrks AuthToken thing if you are using a custom user model because I created a custom user but everytime i create a user there isn't a token taht is generated along with it
django
oh no worries i appreciate u asking tho
@gleaming herald
Try googling gunicorn
Oh
i have my own server
so no heroku
do you have a code or something for quickstart @vagrant adder
Like if I want to improve the number of request it process on flask
Does anyone know how to track my website using Google analytics
I wrote the tracking code and but nothing happened
Yea
To start collecting basic data from a website: Create or sign in to your Analytics account: Go to google.com/analytics Do one of the following:
Did you try this
Four steps in Google Analytics that will help you gain a clear, comprehensive picture of your business.
Concurrency Level: 200
Time taken for tests: 15.718 seconds
Complete requests: 5000
Failed requests: 0
Non-2xx responses: 5000
Total transferred: 710000 bytes
HTML transferred: 180000 bytes
Requests per second: 318.11 [#/sec] (mean)
Time per request: 628.713 [ms] (mean)
Time per request: 3.144 [ms] (mean, across all concurrent requests)
Transfer rate: 44.11 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 3 36.6 0 1056
Processing: 243 618 69.2 607 841
Waiting: 230 604 64.3 596 827
Total: 248 621 75.6 608 1538
Percentage of the requests served within a certain time (ms)
50% 608
66% 636
75% 646
80% 653
90% 676
95% 706
98% 829
99% 834
100% 1538 (longest request)
@balmy forge The test results on sanic
Workers are 2
Threaded = True
Flask gives same result when used with nginx
Hi all
Can someone help me figure something please?
I'm working on a practice website on Django.
It has users and also orders.
There is a User profile page and I'd like to have a list of orders made by that user on that page, next to basic user information.
Can't find a proper example or tutorial as this seems to be a somewhat non-standard task.
How are your Users and Orders currently connected?
If you have a User page, you have the ability to query your Orders based on the User who's page you are on.
@dusky bough Order object has a ForeignKey to User. But the way I'd like to filter them (and that is how I filter them on Admin site) is by "phone" field. Both User and Order have that field so it's easy to filter orders.
Basically, what I'm trying to do is to make a list of filtered Order objects on a User page being filtered by "phone" field.
@gleaming herald I put the tracking code as said and nothing changed in Real-time Overview
I've also disabled my Block tracking add-ons to be easy to be tracked but still
{% load static %}
<!DOCTYPE html>
<html>
<head>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="/static/blog/main.css">
{% if title %}
<title>{{ title }}</title>
{% else %}
<title>Mazen</title>
{% endif %}
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=TRACKINGID></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', TRACKINGID);
</script>
</head>
Here is the code
When I'm trying to deploy my python flask on apache server, on the local host page it just shows a directory of all my files and not the pages itself
What is the hosting service that you use ?
@dense salmon
The best hosting service for python is pythonanywhere so i recommend to host your website there
I was using Apache
This is for an intern thing, they said I should only use apache and not pythonanywhere.
so with django rest mixins i get that there are things like Create Update whatever that are triggered by certain HTTP requests. What request triggers the RetrieveModelMixin?
A GET
Here is a handy table https://www.django-rest-framework.org/api-guide/routers/#simplerouter
Django, API, REST, Routers
@zealous igloo
oh so it's a get plus a lookup, thanks
Does anyone know if flask does any crsf stuff by default? I think its messing up one of my projects but Im not sure.
Is anyone familiar with Apache24 And flask?
I found a very interesting article flask VS django that explain the strength and the weakness of those two https://medium.com/better-programming/python-backends-flask-versus-django-5de314fa70ff