#web-development
2 messages Β· Page 15 of 1
Super, already started with the official docs but will give the other two a look. Thanks!
I haven't checked this tutorial out yet, but Corey's videos are usually the BEST. @novel estuary check this guy outhttps://www.youtube.com/watch?v=UmljXZIypDc&list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p
In this Python Django Tutorial, we will be learning how to get started using the Django framework. We will install the necessary packages and get a basic app...
i recommend him for other stuff too, not just web development
I'm learning python to venture into web development
good call
Learn PHP and use CodeIgniter 4
lol.... I used to use PHP for web dev but Python is cooler π π
I'm writing a new web framework
uu, which kind
a hybrid between flask and falcon
that focus on the requests experience
all the requests data types are present
and you can spawn off a requests session for running your unit tests
I'm not too versed in the world of interwebs, outside casual browser surfing and a small "blog like" django site.
But it sure does sound interesting.
thank you!
@icy fossil got a name for it yet? will it be async?
pls make it asynced
new web framework yay
new web framework seems to happen daily
true
@deep cave Responder. may be async. working on that next
thanks π
soon i think
got some code examples up
@api.route("/{greeting}")
class GreetingResource
def on_request(req, resp, *, greeting): # or on_get...
resp.text = f"{greeting}, world!"
resp.headers.update({'X-Life': '42'})
resp.status_code = api.status_codes.HTTP_416
this example doesn't look quite like valid python syntax π
haha, nifty
I gotta say, I really love how you prioritize Windows support. I don't ever really run my apps on Windows, but I'd really like for users to be able to throw them up without massive headache
I didn't even know Waitress existed but it seems great
starred
$name = $data[0];
$usergroup = $data[1];
$desc = $data[2];
$imgurl = $data[3];
$age = $data[4];
<style type="text/css">
.background {
box-sizing: border-box;
width: 100%;
height: 150px;
padding: 3px;
background-image: url("http://example.com");
border: 1px solid black;
background-size: 100% 100%;
}
</style>
that works together
so
why dosnt It work with html <style type="text/css"> .background { box-sizing: border-box; width: 100%; height: 150px; padding: 3px; background-image: url("<?php echo $imgurl?>"); border: 1px solid black; background-size: 100% 100%; } </style>
(imgurl = a image ending in .jpg)
@neat nest thanks! i use windows myself π
Note : html <body background="<?php echo $imgurl?>"> works but shows tiles and I cant seem to strech it
as broad as the focus of #web-development is meant to be, Stingy, that's... PHP. a little outside the scope of our server
no, the issue is the HTML
Just thought I would add PHP for context
the issue is the style block, I have the html in a PHP file
all I need is a way to put a php variable in this line
background-image: url("http://example.com");```
Such as ```html
background-image: url("<?php echo $imgurl?>");``` (Hope I explained ok)
inserting PHP directives into HTML still seems to me a fundamentally PHP-oriented problem
you'd probably be best served seeking out another server or forum
ok
@tame viper why would it not be valid python syntax?
the class outta nowhere
class blocks are a statement
i dont think they meant to dedent the function tho
Oh ye, https://totally-not.a-sketchy.site/2cd689.png it's just a class with a decorator
mystery solved
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.
@grand badge thanks for the django tutorial link!
So I am tying to display the users following posts
It's a super fancy font, yeah :P
I like it quite a bit apart from that r
hahaha
it's inspired by old monospaced typewriters
very premium typeface
Operator Mono
considered to be the best monospaced font in the world
release v0.0.1 is out
of responder
api docs are here: http://python-responder.org/en/latest/
β
Iosevka best monospace
Any Django-heads in here familiar with customizing user login/profiles?
I'm porting over a Flask-Classful/Flask-Security based app and i'm hitting ImproperlyConfigured: The included URLconf '1' does not appear to have any patterns in it.
can't seem to pin down what could be causing a circular import, except that I have a navbar on the website that has an account dropdown
@icy fossil It's a paid font, you said?
@digital bluff it is indeed
from hoeffler, the most prestigious type foundry in the world
open source is great, but paying for quality is good stuff too
Yea, but i dont like that one enough to pay for it
Wierd font indeed, I thought my browser was fuc*ed up
and I read "index.htme" π
but I'm dumb
Can somebody help me with some css?
I defined one object with text-align: center; but can't define my second variable with the same line. I used position: absolute; but it's janky
body {
background: #000524;
}
#wrapper {
position: relative;
padding-top: 20px;
background: #000524;
border: 1px solid #000;
box-shadow: 0 22px 35px -16px rgba(0, 0, 0, 0.71);
max-width: 850px;
margin: 35px auto;
}
#chart-bar {
position: relative;
margin-top: -38px;
}
p.stock {
text-align: center;
bottom: -10px;
right: 0px;
z-index: 10;
color: #32CD32;
font-size: 72px;
text-decoration: none;
font-family: Century Gothic;
}
a.link {
position: absolute;
bottom: 125px;
right: 225px;
z-index: 10;
color: #ccc;
font-size: 24px;
text-decoration: green wavy underline;
font-family: Courier New;
Anyone good with Django rest framework? I need some assistance in creating serializers
@naive wing what do you need ?
Creating serializers is very similiar to creating Model Forms
Basic serializer example -
from rest_framework import serializers
from .models import Post
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ('title', 'content')
By the way, @naive wing
!t 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.
@grand badge I'm working with multiple model relationship
!t no-dm
Can I send you a private message?
No. We do not provide one-on-one tutoring - you can hire someone locally if you really need that. We also prefer that questions are answered in a public channel as it means that everyone else present is able to learn from them. If you're working with code that you are unable to disclose for any reason, you should try to make your question more general and write a separate, small piece of code to illustrate your problem.
Cool
post your question here so others can benefit from it
what exactly do you want to do with rest framework?
I have an article model and a tag model. I want to make it such that I can create tags when posting an article
oh okay
Well, it's a standard tag system. You can attach an existing tag to an article, and if nothing fits, you can also create new ones
Exactly
from rest_framework import serializers
from authors.apps.articles.models import Tag
class Tags(serializers.RelatedField):
def get_queryset(self):
return Tag.objects.all()
def to_representation(self, value):
return value.tag
def to_internal_value(self, data):
tag, created = Tag.objects.get_or_create(tag=data)
return tag
``` relation.py
from rest_framework import serializers
from authors.apps.profiles.models import Profile
from authors.apps.articles.models import ArticlesModel, Tag
from authors.apps.profiles.serializers import ProfileSerializer
from authors.apps.articles.relations import Tags
class ArticlesSerializers(serializers.ModelSerializer):
title = serializers.CharField(
required=True,
max_length=128,
error_messages={
'required': 'Title is required',
'max_length': 'Title cannot be more than 128'
}
)
description = serializers.CharField(
required=False,
max_length=250,
error_messages={
'max_length': 'Description should not be more than 250'
}
)
body = serializers.CharField(
required=True,
error_messages={
'required': 'Body is required'
}
)
image_url = serializers.URLField(
required=False
)
tags = Tags(required=False, many=True)
author = serializers.SerializerMethodField(read_only=True)
def get_author(self, obj):
"""This method gets the profile object for the article"""
serializer = ProfileSerializer(instance=Profile.objects.get(user=obj.author))
return serializer.data
class Meta:
model = ArticlesModel
fields = (
'title',
'description',
'body',
'slug',
'tags',
'image_url',
'author',
'created_at',
'updated_at'
)
def create(self, validated_data):
tags = validated_data.pop('tags', [])
article = ArticlesModel(**validated_data).save()
for tag in tags:
article.tags.add(tag)
``` serializers.py
from django.db import models
from django.utils.text import slugify
from authors.apps.authentication.models import User
class ArticlesModel(models.Model):
""" This class defines the model for creating articles"""
slug = models.SlugField(db_index=True, max_length=128, unique=True, blank=True)
title = models.CharField(max_length=128, blank=False)
description = models.CharField(max_length=120, blank=False)
body = models.TextField(blank=False)
tag_list = models.ManyToManyField('articles.Tag', related_name='articles')
image_url = models.URLField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True, auto_now=False)
updated_at = models.DateTimeField(auto_now=True, auto_now_add=False)
author = models.ForeignKey(User, related_name='article', on_delete=models.CASCADE)
def __str__(self):
return self.title
def create_title_slug(self):
"""This method automatically slugs the title before saving"""
slug = slugify(self.title)
new_slug = slug
n = 1
while ArticlesModel.objects.filter(slug=new_slug).exists():
new_slug = '{}-{}'.format(slug, n)
n += 1
return new_slug
def save(self, *args, **kwargs):
"""This method ensures that the article is saved with a slug"""
if not self.slug:
self.slug = self.create_title_slug()
super().save(*args, **kwargs)
class Meta:
ordering = ['-created_at']
class Tag(models.Model):
tag = models.CharField(max_length=120)
def __str__(self):
return self.tag
``` models.py
This is what I have so far
I am getting this error
MultipleObjectsReturned at /api/articles/
get() returned more than one Tag -- it returned 2!
@grand badge @native tide
I am trying to ensure that a list of tags is created with an article.
I gtg now, but I will be back soon
@naive wing so do you want to be able to to create a tag at an article list endpoint whilst creating an article?
Yes
do you have a tags serializer?
class ArticlesSerializers(serializers.ModelSerializer):
tags = serializers.PrimaryKeyField(many=True, read_only=False)
class Meta:
model = ArticlesModel
fields = (
'title',
'description',
'body',
'slug',
'tags',
'image_url',
'author',
'created_at',
'updated_at',
'tags'
)
@naive wing im not sure if this will work
but im guessing what will happen is the endpoint will show you the primary keys for the tags in the Article, and then have a create form for a tag as well as an article
it could possibly work
v0.0.2 released: https://github.com/kennethreitz/responder
features async views now
@old gazelle 'fraid I can't help sorry
I downloaded the fonts used on the website, can't say if I will ever use them ^^ (for my personal use I mean, I know they are expensive fonts)
@queen needle its okay, it's css, I just hoped it was an error fundamental to programming that could be solved. text-align: center; should be working honestly, but it's like broken.
I assumed it could've been because of the order in which I defined these variables, and if I'd need to add some JS to allow text-align: center; to work with both objects
Is there anyway I can check how many and which Websockets are connected to django, via shell?
or better... can I interact with the Consumers through the shell?
channels related question btw...
hey guys is there a way to add a full text search bar in python flask
guys, do you know whether it's possible not only to add/install an extension when starting a webdriver via Selenium but also modify its settings? Maybe if I modify the .xpi file?
oof i've been trying to set up flask server for months and until now can't figure it out
so, i have this google cloud instance, it allows inbound connections,
but when i try to access port 5000, it just times out
any of the 'big ports' times out and the small ports like 80 instantly gets connection refused
You're supposed to reverse proxy it with eg nginx
I am following this tutorial https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-16-04
I reached the part where they have port 5000 supposed to appear on the web browser
but then i just have a timeout everytime i attempt connection
yeah but you're not using DO
you're using google cloud
I'd imagine google cloud doesn't open that port
that's why you need to serve it on port 80
oh you're right i thought i had added firewall rules allowing traffic to all ports but somehow they did not show up in this section
should i just switch to amazon ec2?
i mean i was using google cloud just for the free credits
but for the number of months ive been stuck i almost feel i should just use ec2
https://seleniumhq.github.io/selenium/docs/api/py/
Firefox, for example, requires geckodriver, which needs to be installed before the below examples can be run. Make sure itβs in your PATH, e. g., place it in /usr/bin or /usr/local/bin.
*a link is provided to geckodriver-v0.23.0-linux64.tar.gz file
How do I install this gecko driver ? Is it simple a matter of downloading the geckodriver-v0.23.0-linux64.tar.gz file and placing it in the bin/ of my venvironment ? (I am using CentOs 7 64 bit)
That's a gzipped tarfile
you'll need to extract it and see what's in there
although maybe cent has a geckodriver package
@brave mantle
ok, do you know if I need Firefox browser installed as well (apart form the webdriver) ?
of course, yes
I am running on desktopless VPS, thats shoudlnt be a problem right?
@brave mantle well honestly I am scarping 10 sites, 9 of them are doable with just requests and there is one that has lots of javascript on it and requeres simulating inputs clicks and etc
Are you sure doing this doesn't violate the terms of service for those sites?
yes, no worries,they are owned by the corporation I work for.
anyone ever actually get django-channels to deploy under an nginx proxy_pass via daphne and work? this deployment is making me want to use Node.js
good heavens
are you using connection upgrade
upstream channels-backend {
server localhost:8000;
}
...
server {
...
location / {
try_files $uri @proxy_to_app;
}
...
location @proxy_to_app {
proxy_pass http://channels-backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
}
...
}```
oh yea, haha im past that part, here i can post more specifics
upstream app_server {
server unix:/var/run/gunicorn.sock fail_timeout=0;
}
upstream ws_app_server {
server unix:/var/run/daphne.sock fail_timeout=0;
}
# HTTP
server {
listen 80 default;
server_name localhost _;
server_tokens off;
return 301 https://$host$request_uri;
}
# HTTPS
server {
listen 443 ssl backlog=16384;
server_name localhost _;
server_tokens off;
ssl on;
ssl_certificate /srv/ssl/self_signed.crt;
ssl_certificate_key /srv/ssl/self_signed.key;
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers EECDH+CHACHA20:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;
ssl_prefer_server_ciphers on;
client_max_body_size 250M;
root /srv/app/static/;
index index.html index.htm;
location /static/ {
alias /srv/app/static/;
autoindex off;
}
access_log off;
error_log /var/log/nginx/error.log;
location /ws/ {
###
# WebSocket App ProxyPass
###
proxy_pass http://ws_app_server;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass_header X-Forwarded-Host;
proxy_redirect off;
}
location / {
try_files $uri @proxy_to_app;
}
location = /nginx_status {
stub_status on;
allow 127.0.0.1;
deny all;
}
location @proxy_to_app {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass_header X-Forwarded-Host;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://app_server;
}
}
this "works" i suppose but still getting root_path issues with daphne, if I can get an error to show I'll post that instead
Hey guys, is someone here who knows about userinterfaces on websites
I have a very weird implementation of a login here and wanted to know how [whoever did this] he/she did it
user interfaces on websites seems kinda broad, post a link?
~~I've been puzzling over this with a Django template and have went through the documentation (at least all the possibilities I'd know to look at) and similar stuff on SO to no avail, so I thought I'd ask here.
Assume something like this has been added to a view's context:
animals_dict = {
'birds' : ['parrot', 'cockatoo', 'robin']
}
I'm looking for this sort of functionality:
for type in animals_dict:
print(f'{type}:')
for animal in animals_dict[type]:
print(animal)
within a Django template. I've tried a few permutations of things similar to...
{% for type in animals_dict %}
{{ type }}:
{% for animal in animals_dict.{{type}} %}
{{ animal }}
{% endfor %}
{% endfor %}
but they turn out like
django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '{{type}}' from 'animals_dict.{{type}}'
Anyone know of a way to implement this or some search terms that'd get me pointed in the right direction?~~
~~Quick question, I'm pretty new to routing urls using Flask Restful, https://flask-restful.readthedocs.io/en/latest/, and I was wondering if it was possible to route multiple urls to the same resource by doing:
@api.resource('/api/public/tokens')
@api.resource('/api/public/tokens/')
@api.resource('/api/public/tokens/<string:id>')```
without having it throw `AssertionError: View function mapping is overwriting an existing endpoint function: tokenTest`?
Basically what I'm wondering if it's possible to route multiple urls to one resource without creating said resource multiple times?~~
Nevermind I just figured out that `api.add_resource()` is a thing. Thanks in advanced!
Found a solution to mine, too. Convoluted, but:
First, creating a custom template tag to retrieve the list like so...
from django.template.defaulttags import register
@register.filter
def from_dict(key, dictionary):
return dictionary[key]
Then in the template...
{% for type in animal_dict %}
{{type}}:
{% with type|from_dict:animal_dict as animals %}
{% for animal in animals %}
{{animal}}
{% endfor %}
{% endwith %}
{% endfor %}
@slender shale can't you just iterate over animals.values()?
animals is a list
ah
did you try this?
{% for type in animals_dict %}
{{ type }}:
{% for animal in animals_dict[type] %}
{{ animal }}
{% endfor %}
{% endfor %}```
its super hard to read what you posted
actually why wouldn't this work ```django
{% for type, animals in animals_dict.items() %}
{{ type }}:
{% for animal in animals %}
{{ animal }}
{% endfor %}
{% endfor %}
You do know that you can't use () or [] in Django template tags right?
I need some assistance in django rest framework, anyone?
!t 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.
anyone know web2py framework?
You'll have better luck actually posing the question @sharp flame
XD
well, i have a few then, lol
how do you do radio buttons, and how do you make a form, using =form.custom
Does anyone know how I can parse discord chat with Greasemonkey to trigger a keyword notifier? I can't identify where the stream exists
You cannot, that would break the terms of service
Ah, good to know! Ty
say what now
@digital bluff - Basically Discord is lacking an important feature... keyword notifications. There's been an open request for the feature for 3 years now - https://feedback.discordapp.com/forums/326712-discord-dream-land/suggestions/10661937-highlight-words-for-custom-notifications-mentio
I thought about building it myself, but since it's against the rules I don't want to get in trouble
It's kinda surprising this doesn't already exist as many other chat clients have it
@sharp flame Seems like nobody has an answer for you
Maybe it's time to peruse the docs again
@untold parcel Keyword notifs are often used as a spying mechanism
If people want you to be sure you'll see something, they'll mention you
that can't be Discord's justification for not adding it. There's clearly a lot of demand for it and the feature already exists in Slack, IRC, and many other chat clients
Slack because it's designed for teams, IRC because there's no concept of a mention
I dunno what their rationale is but that's why I wouldn't add it
XD
my web framework is coming along!
@icy fossil Nice! Did you make a decision on aysnc yet at all?
i think async is already implemented
it is indeed
Awesome!
@icy fossil can you still use the framework without async?
@icy fossil how did you implement async so quickly?
the magic of open source.
31 contributors already
but also because holy shit kenneth committed 339 commits and nearly 60k lines just this month
that's some off the charts productivity.
I need to port some Tornado code, should I use responser instead of aiohttp then ? π
import flask.ext.sqlalchemy as flask_sqlalchemy
ModuleNotFoundError: No module named 'flask.ext'
trying to use Flask-WhooshAlchemy
keep running into this error.
are u sure whoosh alchemy is installed
@hearty birch follow the docs, they seem pretty nice
https://flask-whooshalchemy.readthedocs.io/en/latest/
@hearty birch afaik this system is deprecated. You need to install flask-sqlalchemuly and then import it as flask_sqlalchemy
From my project, this is in the requirements (what you need to install):
And you call the extension in the code like this:
so to use whooshalchemy i need to have flask-bcrypt and httpauth? or am i misunderstanding something @unique folio
That's just an example @hearty birch
Use whooshalchemy as I did bcrupt and httpaith
Sorry didn't make that very clear
ah yeah, I have imported them like that, the error is raised by the actual package, I think it uses import flask.ext
@hearty birch I see. I think I have a fix for you
go to to where your flask_whooshalchemy package is located and edit
import flask.ext.sqlalchemy as flask_sqlalchemy
to
import flask_sqlalchemy
hm. but then everyone who installs flask whooshalchemy through pipenv will receive the incorrect one, and would have to change it manually
i think this package is outdated and not maintained, but not sure
well the last time they updated the package was 2014, so I think it's fair to say it's outdated
ah
this sucks cause the extension is very useful
how else would you guys recommend implementing some sort of search feature?
i currently have a flask project which is designed to query a database and then return the query in a pandas dataframe, which i then do df.to_html() on and display it on the webpage.
I'd like to be able to have the query change based on the user input with a drop down menu on the page, and then when submitted have the table update with the new values. Is there a way this can be done in flask without using javascript? or is this sort of dynamic content really only going to be possible to do with javascript?
couldnβt you use regular HTML forms and use the params in those to change the way you display it?
If you want to update without refresh you likely need JS
yeah so i'm using wtf forms at the moment to do it and thats all good i was just hoping there would be some way around using javascript. Currently i don't know it and i don't really want to learn it right now.
i've just decided to refresh the page and keep the template identical between pages, since the query runs quick enough to the user it just looks like the table is being refreshed while everything else stays the same. Perhaps not the best solution but hey it works for now
@native tide I just completed a project similar to your where pandas was presenting its dataframe contents and I found it way easier to just use JS for some simple REST requests to flask to have the flexibility of styling and functionality. You are eventually going to have to learn JS so I recommend learning the evil now rather than later. (If you need a JS framework, I recommend VueJS which is very lightweight and does as much as you need it to.
hey dudes, I am a newb when it comes down to php, and I can only read html. I have set up a Wordpress website locally with xampp and I have created a Woocommerce site. My question is, is there any way of sending license keys with an email after the purchases?
I know that there are some paid plugins for it, but I am pretty sure that this can be done with some coding changes as well
where is the connection to python?
@dusk spire yeah the more I think about future project ideas the more I realise I'll need to dig in to JavaScript to do what I want.
So did you just convert the data frame to. Json and have the JavaScript pull the data out to present it?
Also what did you find was easiest to make the REST endpoint? That's something I've been putting odd as well haha but I have looked into flask - restful before, is that the way to go?
@native tide I did exactly what you said, told pandas to convert the dataframe into json (orient='records') and then adding that content into a v-for loop inside of a table with bootstrap. In terms of the REST endpoint, if you want to use python definitely use Flask because of its established record and faster than django's rest framework. I just used vanilla Flask instead of Flask rest api because I had issues with the REST api framework not allowing for parameters in the url in the way I wanted it to.
@dusk spire alright thanks for the help mate, Its good to hear how you've done it, it gives me a better picture of what I'll need to do. And I guess that means I'll have to finally stop putting it off and go learn these things now as well haha.
If you need any help, feel free to send me a dm with any questions
@native tide i am assuming from here https://github.com/cloudflare/sslconfig/issues/8
or
somebody made a tutorial based on that
and he got it from there
3DES :/
the guy in the issue states that they are seeing some 3DES traffic
Β―_(γ)_/Β―
so maybe its still out there
That was considered questionable when it became standard
hopefully not though
true true
i wonder if chrome would even suppot 3DES
1.3 is coming scott
i am surprised
chrome allows 3des
@native tide yeah lifted from some other trash, it's already back to 1.2. my rev proxy doesn't even use 1 or 1.1
Naw, lots of people dropped 1.1 and under
Sorry Android 4.4 and under
apigee
Anyone using djangocms here?
Hi , can anyone tell me what i am doing wrong ? ( i am beginner ... )
from bs4 import BeautifulSoup
import requests
result = requests.get(webpage)
webpage = "https://www.calmac.co.uk/service-status?route=11"
websource = request.urlopen(webpage)
soup = BeautifulSoup(websource.read(), "html.parser")
span = soup.find("div", {"class": "topbordershadow"})
print (span)
@north surge can you show us what is wrong, post the error please
sacrilegious question: Does anyone know of a javascript discord? I have a JS problem I cannot solve.
@fervent glen you can post your javascript questions in here
What happens in flask when multiple requests come while the old one isn't done computing? I deployed a prediction API and it becomes extremely slow when multiple requests come in a short period of time. Is there something I can do to prevent the slowdown?
If you are using flask it'll process them one after another
You can use WSGI servers like for example Gunicorn to spin up multiple parallel instances
You should also not use the flask development server in product
Ion
I am using azure web apps for deployment
I should've specified that
I guess I have to set it up there
Javascript question: I have a variable 'cart' which is a dictionary that I store in localStorage. When a user picks a new item, I want to update the dictionary, and if they have selected a new item, not just updated the quantity, I want to add a new key to the dictionary and store its related values. I don't know how to dynamically create new keys. Here's my logic in pseudo code:
for item in cart:
if item[size] != size and item[color] != color:
create new key and store values
else:
item[quantity] = quantity
and here's the logic for storing the item's values:
javascript
var cart = {
item : {
size: $("input[name='size']:checked").val(),
color: $("input[name='color']:checked").val(),
quantity: quantityToSave,
imgSRC: image,
}
};
from flask import Flask, render_template
app = Flask(__name__,
static_folder = "./dist/static",
template_folder = "./dist")
@app.route('/')
def index():
return render_template("index.html")
app.run(debug=True)
simple flask app
but it is not finding index.html
this is the file structure, so should in theory be finding it
Looks like you are runing your app from backend folder which is on the same level as dist
So you would have to go back one to find it "../dist"
But I would sugest using the standard structure of an app where you have an app folder and put your templates in that folder
app/
---templates/
---static/
---__init__.py (contains app init)
run.py (imports app from app)
If you are just learning Flask I suggest a quick skim of this tutorial
https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
@hearty birch
ah yeah I figured it out
and nah its not my first time using flask i have used before
its just i wanted to experiment with a vue.js frontend
whenever I run npm run build it goes into that dist folder so then flask can serve the inital index.html, and then vue.js does the rest of the routing with vue-router and the history option
any django experts on right now? I got a question about .filter() - I need to grab all instances of a model that DO NOT have a populated FileField (i.e the ones that don't have a file attached to them). I know that FileFields are falsy when empty, but can't figure out how to specify that using .filter()
could anyone lend a hand?
nvm figured it out. looks like an empty string is the way to go
i.e something.objects.filter(yourfilefield='')
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.
Are we allowed to seek people who are willing to do paid development work in this channel?
I'm afraid not. you can do that in off topic channels. we are working on a system for this, though. in the future there'll be a channel specifically for this kind of thing, but we're still figuring out the format.
Do any of you guys have experience with deploying a Flask app via Azure Web App? I'm running into a problem where I'm deploying a prediction API and after a while it takes forever to get a response for the first time, but once that's over it's fast again.
I have turned the Always On option on. At first I thought it's loading the files needed for prediction what takes a long time, but that takes about 2 seconds. I tried to access the website portion through browser and it was fine, but then I sent a request to the API and it took 70 seconds to respond.
I also put time.time() on top and bottom of my API function (under website.net/predict) and that reports it took 1.7 seconds to process, but the response took 77 seconds to get to me. When I send another request, it's fast as it should be. Any idea what might be causing this issue?
__init.py__
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)
from api import routes
from api import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(120))
password = db.Column(db.String(120))
def __repr__(self):
return f"User ({self.id, self.username, self.password})"
when running db.create_all in interpreter
no tables are created
Hmm, im working in flask page where users need to give their country and city
What would be the best way to store that in database so that i can look it up later and nit have users that are from nonexistent locations
I was thinking of Some sort of autocomplete on input maybe
But i want all locations to be stored at database in a single format
i'm enjoying using responder lately
It was on Python Bytes yesterday!
d
*insert story/excuse here*
I'm currently doing this for applying css templates to pages.
Is this fine or is there a more straightforward way to do it?
style.html
<!DOCTYPE html>
<style>
html {
background-color:#010903;
}
</style>
<html>
{% block content %}{% endblock %}
</html>```
`home.html`
```html
{% extends "style.html" %}
{% block content %}
<body>
<body>Test content!</body>
</body>
{% endblock %}```
I should probably state that I'm using Flask, for context's sake.
Hi guys I am new to flask have been trying to display some data on my flask page from an api json but when I try to only get 1 element I keep getting errors but when I print the json_data it prints all of the data. Any resources you guys know that could help me?
@keen plume awesome, i didn't know, thanks!
i want to make a html form which can take images from user and save into my local storage ... i am done with the form part but how to get images to get saved into my computer
@deep cave
what framework?
i guess you would have a db, let the user upload image via the site, and do some juju backend magic for the rest
no if the page is local i wont need a data how can i do that @grand badge
you'll still need a db even if its local
i have a question. lets say i wanna run a python script every day. i wanna run the script every day at 9 am for example. i have heard a lot about raspberry pi 3. is it possilbe that i can create my own server on that and run my code every day?
i was also going to ask whether if i can do it on a web server
i mean for example i created a website
yes, you can use your rpi as a server but i wont do that if i were you
because if you use an rpi as a server, that rpi is going to be on your network, which means that you have to pay more attention to security
so whats the best way to do such a thing?
to host a website?
well there are a lot of options. Does your website have a backend?
it would have
i dont have a website right now but im plannig to create one
and yes it will have backend
I heard DigitalOcean is good. If you are planning to make your backend in python pythonanywhere might be suitable
alright will check it out
You can also try Heroku
do we have a channel about rpi?
no
i guess ill just ask my questions on python-discussing
hmm
with question, i mean im really interested in rpi
wanna know more about it and what things i can do with it
@meager anchor where can we talk about rpi related issues relating to python? #tools-and-devops or #python-discussion ?
oh yeah, forgot about that channel :D
name's Chicken McBwok
I asked a minor question earlier, just in case anyone more experienced with Flask happened to be around.
hi guys, is django question acceptable here please?
i am new to django, have to deal with a site, which has an existing basic form/model/view relation, it just modifies the value in the model, nothing interesting. i need to somehow modify behaviour, so instead of updating the value from model i increment it - completely stuck. should i overload save for the model? should i create a new model, refer it t the old one, and overload save there, updating both models? should i create a virtual property, put that property in the form, and update the needed property afterwards? should i use pre_safe? i feel i am overcomplicating the issue because i am now to the framework.
i want to make a html form which can take images from user and save into my local storage ... i am done with the form part but how to get images to get saved into my computer somebody help me with is in DM
@native tide as in you have some form of counter field? Maybe you want to use a different widget? this seems like logic you want on the frontend
@verbal panther depends on which framework youβre using and weβd also have to see your code
additionally
!t no-dm
Can I send you a private message?
No. We do not provide one-on-one tutoring - you can hire someone locally if you really need that. We also prefer that questions are answered in a public channel as it means that everyone else present is able to learn from them. If you're working with code that you are unable to disclose for any reason, you should try to make your question more general and write a separate, small piece of code to illustrate your problem.
@meager anchor it's more aggregated value field. say, it was "100", and user1 comes, adds 10, it becomes 110, user 2 comes and adds 100 - it becomes 210. now it's just linear form, i need to change it into historybased values.
right now if both users will edit it at once one of the changes will be lost
Hey guys I'm trying to write a websocket which will loop an api request and every 5s send data to the client. The reason I'm doing this is because I have a betting api setup but need to update the odds live every 5-6s. What do I need to use in websocket to call this. Do i loop the websocket and then call onmessage from the client every 5-6s or can the server send the data after it gets it ? I'm doing this with flask and flask-socketio
hey guys,
I'm trying to make a small project with my raspberry pi. a small weatherstation on a website.
the temperature sensor is connected with the GPIO and a script outputs the temperature every X seconds in the console with print().
now, my question: how can i display the stdout on a flask website or let it communicate together? I don't want to make it a request every X seconds. So is there any way to make this possibly work?
youβll need to read the sensor value out on the flask side
or share it through a file
okay and how could i let it change the sensor value dynamically without refreshing the website?
websockets? π€
maybe that, or just have a looping js call to some other endpoint on your website that responds with the value
that is actually a good idea. thank you π
hello - anyone in here ever use typeahead.js and bloodhound? I'm wondering if there's a way I can reduce prefetching time for a large json file by using some other method of bloodhound
The file is ~6mb so it takes 5-6 seconds to prefetch but it also updates every day so caching is kinda non-ideal
Anyone know a good react JS focused discord?
found one
Hi all I have a n+1 problem with Django Rest Framework right now. Trying to do select_related and prefetch and its improved calls a bit but still really slow. Hoping if someone thats done this before can take a look at the code and see where I can optimize.
i bring you the first website on the world wide web: https://www.w3.org/History/19921103-hypertext/hypertext/WWW/TheProject.html
Hello,
I'm working with JWTs for the first time ever in a web application using a vue.js frontend with a flask backend, and I am confused on how to do signouts.
This is my current logic for the signout component: https://pastebin.com/u7nYCn7T
This is my invalidate access/refresh routes code: https://pastebin.com/aerKh0RD
Am I doing this stuff correctly? How would you do it?
Furthermore I am extremely confused on how to handle refresh tokens.
With every request requiring an access token, should I verify the token hasn't expired there and then if it has, try to generate a new one with a refresh token, and if that fails, prevent the request and tell them to sign in again?
Or... What?
How to get images to my folders from my sql
!t 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.
I am using flask to create a website and I am trying to set a domain and I cant get it to do anything
how are you trying to set the domain
app.config['SERVER_NAME'] = 'testoo.xyz' @opal leaf
app.run(debug=True, host="0.0.0.0", port=8080)
so what do you expect that to do? you still need a dns server to recognize that you want to use that domain
and the links on most flask sites will use whatever domain/ip you used to access it
so unless your dns server assigns testoo.xyz to your servers ip you wont be able to use that domain name to access the server
you can test with your operating systems HOSTS file though. and map the domain to your ip there
ok so then how can I open my app to the world
the flask documentation recommends against using flask itself as the main server, they have a page on deployment in their documentation.
youll have to get a domain name pointing at your ip address [and if you are hosting it at home it can change occasionally]
and then forward a port with your firewall
also be aware that if you have any bugs in your code, hosting it at home has a lot of security risks
might be better to host it in a VPS (virtual private server) that you rent from someone, or some python specific host
How long do recaptcha tokens last for?
Responder's hello world (from the homepage) now performs at 1414 r/s on my machine, with a single process running.
any frontend/full stack gurus in here?
!t 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.
@icy fossil how does that compare with other web frameworks? just curious :D
I fell in love with Phoenix so I gave up Python when it comes to web development
how can u use python in web development ?? ;D
Hi all, if I want everyone to see django-debug-toolbar when I runserver 0.0.0.0 and link it to them what do I need to do? I thought I set REMOTE_ADDR to my public ip but that is not working.
What is a good website development package to get me going
flask might be a good choice to get your feet wet.
@slate solstice there are several popular web frameworks for python. you can write your backend in python, generare the html via marrying python with a templating language, and even transpile python to javascript via something like transcrypt
maybe you should try it out. python webdev is fun and satisfying
I will take a look at itπ
In order to update a website, what do I need to do after pushing the new file to the FTP server
I updated the file last Thursday, looks fine when I look at it now. The old text is still being displayed when I load the website and websniffer.cc is showing no update since july
depends entirely what kind of website it is and how it's being served
apache
okay. try restarting the apache service and see if that does the trick.
normally for a flat html page you shouldn't need to, but
worth a try
and make sure you're not just seeing a cached version
visit the page in private browsing mode or something
I have done that a couple times, yeah
yep, well then it does sound like it's still serving the old one for some reason
can I restart the apache service from dreamhost or is that a separate service?
I don't know what dreamhost is
sudo service apache2 restart on the server oughtta do the trick
if you have access
you're right about that :P
there's only so much I can do for you if you don't have access to the server
ask dreamhost support I guess
yeah I don't
I don't think
unless the guy we paid set up something weird, which i doubt
well this is sounding kinda dreamhost specific
yeah could be
just sent in a ticket
wanted to make sure I wasn't doing something dumb like forgetting to commit or something
whatever system they have over FTP is gonna be completely custom, tbh.
who knows what happens after you transfer it
just follow whatever guides they have and as long as you've done that, I guess you've done everything you can.
np. and do consider a real server instead. it's a great opportunity for learning, you get total control of everything, and it doesn't have to be expensive.
sure
am i right here if i want to know how to let python read data from a website and print it to the cmd ?
that's not really web development, but you should look into something like requests
and perhaps beautifulsoup or something like requests-html or scrapy
you wanna do something called web scraping
@native tide
waht I mean is i was not sure if you were on pc or mac
Ohh on Windows PC
ctrl f5 works on pc for clear cache refresh
I got this
but idk if there is an equivalent on mac
nono
Hm?
go to your browser
Mhmhmhm
Go where?
what browser do u use?
I don't see what you mean?
you dont have to but its good practice
what did you add?
html
nope
Why?
you need to add the <link> tag in your html
all tags go in html file
just like any other tag
So, wait I add the link tag in html
So how would it be just like this
Html tab
<link>
That's all?
or link then <link> index.ss
I literally am so terrible at this sorry
you have to add the relevant link attributes too
dont add link in css
index.html
<head>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
You're amazing.
Thank you!
Hope this works
WHOOO!
It works! π
Thank youououououo! π
π
@grand badge Once again, thank you for helping me, I'm very clumsy at this stuff hahah
right click and check for browsers?
change your system's file associations?
HI i'm trying to write a simple api and was wondering what do people use for authentication and authorization. I'm using the falcon framework (https://falconframework.org/)to build this api.
@tight verge https://jwt.io/
thanks @lapis raven . What do you use for authorization or role based access control?
@tight verge I decorate my endpoints with a function that intercepts the request, pull out the token from the headers then use a jwt lib that can verify the token using my secret key. For roles I use a roles model that has a relationship with users, such that doing
user.roles
gives all the roles associated to that user and I can verify that the use can indeed make that request. Also for each endpoint you can assign it the roles a user has to have in oder to access it. Look at the screenshot, example signature for a post verb for some resource.
thanks again @lapis raven
Hey!
been at this for a while now, anybody tried to do something similar π¦
I'm having some issues with my Django Rest Framework . ```python
class GroupResourcesSerializer(ModelSerializer):
"""
Serialises a Group into JSON with deterministic field output. Groups lookup is by name.
"""
# Reverse many to many lookup
content = serializers.StringRelatedField(source='resource.groups', many=True)
class Meta:
# Define the model to use.
model = Group
# Define the fields to return.
fields = '__all__'
extra_kwargs = {
'url': {'lookup_field': 'name'}
}
I want to do a reverse lookup of the many to many field defined by Resources. But I get an attribute error. The JSON output I want is something like...
```json
# Groups
[
{
name: String # The name of the group defined by the model
desc: String # Description of the group defined by the model
content: [array of resources] # Defined by the many to many rel at Resources
}
]```
Fixed
Does anyone want to start an ecommerce site with me (written in python). Probably shipping tech (or something else, open to suggestions) maybe dropshipped from ali express. DM if interested.
@native tide We don't have a recruitment system at this time
Really?
So then what's the best way to get ppl to join a fun collaborative environment?
Lol the r/ReactJS discord does so idk
okay that makes sense. can i still try to recruit lol π
also btw i have a startup that competes against Slack, Monday, Trello, Asana, and Microsoft Teams so if you need help lol I might be able to, because we have legit become experts on channel based communications π
Is it just me, or is infrastructure/configuration of code the only sane way to do things nowadays
I'm starting to get my head around serverless and aws lambda/api gateway
and realising how powerful it can be.
@dusk junco
https://stackoverflow.com/questions/34219615/django-migration-x-in-app-x-has-no-migration-class
thanks
can i actually learn css through django video? haha
got the basic already, using bootstrap framework but creating an awesome website i think pretty hard.
@dusk junco well you could learn some css through a django video but i wont recommend it
you're better off searching for a video to do with html/css development
i see , thank you
can i learn django first though before learning css bootstrap and design a "cool" looking website?
anyone good with nginx here? I'm having a problem where I can't serve my static files from nginx
!t 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.
well nvm I fixed it. Had a problem making docker nginx serve static contents. It seems that it needs absolute path to work
Lorem ipsum dolor sit amet
Hey guys how do I go about making use of a subdomain for static files. I have the domain setup but it can't seem to find a way to redirect the static files from domain to subdomain. Do I hardcode it?
.. redirect?
youβd just use an extra virtual host in nginx
with the server name set to the subdomain
the problem is that it doesn't work.
I'm trying with proxy pass and that way I get error 404
this works but it doesn't pass through the subdomain it skips that somehow
/static/(.*)```
nvm it seems cloudflare sets that cookie π
if you get 404 where you think there would be files, turn on debug error logging and nginx will tell you where it tries to load the file from
it was working fine just it seems that cloudflare addess a cookie which can't be disabled
Apache2.
if I want to properly sanatize input for html use do i just have to replace the < and > characters?
well damn, ok. Guess there really is a module for everything
also yeah i forgot & but i was escaping that too
this is what I have rn because I dont want to just sanatize the html
def postToHtml(post: str) -> str:
#dict of text to escape to sanatize html
escape = {"<":"<",
">":">"}
#dict of html to insert to format post
replace = {"\n": "<br>"}
htmlstring.replace("&", "&")
for seq, esc in escape:
post.replace(seq, esc)
for seq, rep in replace:
post.replace(seq, rep)
return post
I removed the & first so that the &'s generated from cleaning up opening and closing tags dont get expanded obv
I've seen code that also escapes qoutes tho, why is that?
you forgot the semicolon on >
because you might want to put it in an attribute
e.g. <img title="some text"> for hover text liek xkcd
this is all explained in the documentation for html.escape, which has an option to do that
anyway, you should use the stdlib function
ah i see
but if you're going to do something like this yourself, i would suggest a regex to do the replacements in one pass
ok, so i think ill use the html.escape function and then just use regex to search and replace with needed html tags
def mysub(m):
return {'<':'<','>':'>','&':'&'}[m.group(0)]
def postToHtml(post):
return re.sub('[<>&]', mysub, post);```
when you pss a function to re.sub, it receives a Match object as argument
m.group(0) returns the matched text [1, 2, etc, return capture groups]
and beyond that is just looking up in a dictionary, which you were already doing
alright. I think ill probably end up doing that then, thank you
er
for the html escaping you should use html.escape
but that'd be a good way to do your other substitutions in a single pass if you have any
sorry yeah i meant that im using html.escape and then regex for replacing with tags
thanks
Hey guys
This may be a bit of a noob question,
But web application development is a different to website development right?
I know there's a huge overlap, but I'm pretty sure I want to get into web application development. Solutions for business logic problems etc.
we just call both web development
they're basically the same thing
although when people say "web app" they usually mean a website with extra added functionality
hey how do I use flask current_app inside already created app context (I ? I want to use the app.before_request decorator but it gives me RuntimeError. It doesn't make sense to create another instance of app, since it doesn't affect the original one.
I'm using factory pattern
Nevermind, created the before_request function inside create_app
Hey, I making one project witch one requires login, ( would be maximum 20 users, no registrations , just need to link to separate wb pages with login and password) i tried do with php but i totaly lost in there ... running in to problems ... can anyone give me advice how simply i can make login system on py or other language ? just simple on π
Hi, has anyone ever try to create Jupyter widgets before? I'm curious what approach, lib, or js-framework that people use thinking
Is there anyone that needs a full stack developer, paid project or unpaid is fine. DM me if you have a project.
@north surge django has an easy to use authentication system
I'm looking for a python date parsing library. Any suggestions?
I have a string value of Time: 6pm β 9pm but when I perform 'Time: 6pm β 9pm '.replace('-','') it doesn't remove the hyphen.
@timid arrow thanks. I found a blog article reviewing several libraries. dateutil was mentioned. Although I'm currently experimenting with moment
Anyone used lxml? is there a reason to change from beautifulsoup to lxml?
I'm having an issue getting this to work
foo = ('.', '_', '<', '>', '(' , ')','$','{','}')
if "/fruits/apples/$.drop('STUFF')" in foo:
print('yes')
@thin axle lxml is quite old fashioned and kind of a pain in the ass to work with, but veeery fast. bs4 uses it to parse xml, and you can choose to use it to parse your html too if you just pass in a "lxml" argument when you call the BeautifulSoup constructor.
they're not reaaally the same thing. bs4 is much more high level and has other sort of high level conveniences.
oh, thanks very much for the description
thats exactly the type of answer I was expecting
if you want to look at an alternative to BeautifulSoup, you could check out requests-html, by kenneth reitz. it's fairly capable, and iirc it uses lxml for everything.
in its backbone.
it has full support for parts of the website generated with javascript - which is rare to find in other libraries that do the same thing - so it's a fantastic choice if you're running into issues with that.
also it's got all the For Humansβ’ magic you're used to from other reitz projects :)
@autumn hedge not sure you're in the right channel and also what is it you expect that code to do?
that string isn't in your tuple, so it's gonna be False.. were you expecting something else?
maybe you wanted to see if any of those signs were in the string?
@deep cave yes. I figured it out.
foo = ('.', '_', '<', '>', '(' , ')','$','{','}')
has_str = False if "/fruits/apples/$.drop('STUFF')".find(" ".join(foo)) == -1 else True
if has_str:
print('yes' )
is that considered pythonic?
not really.
the False if .. else True parts are totally unnecessary because an expression that compares two things with == is already gonna be a boolean
in other words, it'll do the same thing if you remove those.
i didn't know requests had this html brother
i love using requests
beautifulsoup is ok, but i dont like the syntax. Thougth lxml was a bit closer to "original" v8 engine
thats why i asked
good point.
a pythonic approach might be something like
foo = ('.', '_', '<', '>', '(' , ')','$','{','}')
check_string = "/fruits/apples/$.drop('STUFF')"
# Using any() and a generator expression
if any((char in foo) for char in check_string):
print("yes!")
# Using a simple loop
for char in foo:
if char in check_string:
print("yes!")
break
and ideally foo would be a set
@autumn hedge that's not a hyphen, it's '\u2013' en dash
@polar wasp can that character be converted into a hyphen? How did you determine the type?
I copied and pasted it into https://www.fontspace.com/unicode/analyzer/
Find out what unicode characters are in a string of text
I don't think there's any built in way to auto convert that would work any better than just using it instead (or in addition) in your .replace
Hello,
I'm pretty new to web dev work, normally do data analysis with python. But I was wondering if there was a good place to get free (no linking to website or author) mathcing social media icons for a contact me webpage. I know its a pretty basic question but the second you google free it gets really difficult to find anything.
Honestly it might be easier for you to just get the actual logos and edit them in something like Photopea (https://www.photopea.com/) and force them to be monochromatic
@cyan zodiac
thanks!
Also this was my first search result, in case you hadn't found it yet: https://www.flaticon.com/packs/simpleicon-social-media
What alternative is there to SQLAlchemy for ORM?
PonyORM is pretty interesting
there's also DjangoORM, but that's for Django only - and if you want something similar to that for other frameworks, you can try PeeweeORM
Quick sanity check: I'm using Django's ManifestStaticFilesStorage and when I run collectstatic it adds new files to STATIC_ROOT but doesn't remove the old stale ones.
Is this how it's supposed to work (ie. I just keep accruing more and more styles.[hash].css files), or should I always be running collectstatic --clear?
is the best thing to do for web development to use flask for small projects and django for larger ones?
i wouldn't generalize it like that
both are great frameworks, flask is easy to get up and running with for simple stuff, django gives you a lot out of the box once you want to add database and caching and whatnot
my website is rather small and runs on djang
Flask: Batteries not included; buy your own batteries, any brand
Django: Batteries included; no say on what brand of batteries used, django batteries ftw
@steel tiger
yes
i guess for a large project you might want to use django then
but on the other hand
if you want to do a large project with nosql database then you cant use django
so it really just comes down to preference at the end of the day @steel tiger
you can use nosql with django. it's just probably a bad idea.
our site used to be in flask
http://shop.oreilly.com/product/0636920032502.do I've heard good things about this book
but according to g, it was like half of django
but I haven't read it yet
supposedly it's possible to use Django in a more flask-like manner
it just requires a bit of study
it was more like all of Django. we implemented our own migration system from scratch.
we wanted an ORM and to move from nosql to sql
we had our own weird form builder thing
I mean.. it's still running flask but the django rewrite is coming along

eventuallyβ’
anyone tried alexa with flask-ask? (not sure if this is the right place, its using flask but its alexa)
Hey! I have a flask database related question, anybordy here?
So I have a database that contains blog posts, and upvote scores, a little bit like reddit
And every time a user renders the homepage I want to display results in a particular order..
That order should depend on the difference between post-date and the current date
I have thought about a few ways on how I could tackle this:
- Javascript
- Celery or RQ (or cron, but I don't want to lol) that creates a ranking column in my posts
Any ideas?
@deep cave does the book that you linked, is "updated" to Django 2.x or just don't make "difference", not a django guy yet π
2.x is a big change, but most of it is under the hood
it's when django went python 3 only
so in terms of how you actually use it, there are only a few minor changes, like not needing regex in the url patterns and some changes to the admin panel iirc
anyone here used quart? i have to rebuild my web-app from the ground up and i'm thinking of switching from flask
@deep cave ty, gonna buy it when i got more experience with Django 
How come with django when I switch to my postgres database all the admin panel css goes to shy
@native tide did you try migrating again after changing?
I was also just looking into quart, but now I don't think I need to go async so I probably won't yet. It sounds nice to get better performance, but from what I understand if you are doing anything else like db or file io you will be constrained by that if it is also not done async, so you may or may not really see all of that performance. For example I found https://github.com/aio-libs/aiomysql but I didn't dive into that.
yeah.
hello! I am looking to build a website where I can call multiple api and display them on the same page. I want to know where can I start looking to build this project
is there a way in flask to return a status code (such as 102: processing) without closing the connection?
@orchid whale could AWS API gateway do this for you?
@native tide is your problem on a server? or is it a local problem?
Hello guys. I want to create a html document like the picture below. I dont have any knowledge about html and i want to create something looks same as the picture below as fast as possible. What topics should i search for to do this?
both
hmm
Hello !
@oak niche which part of it are you having trouble with? That seems like a pretty basic layout and I'm not sure exactly what you're asking
Greetings
I have a question regarding flask
I was going through flask tutorial on the official website but at the point where I have defined the "create" I kept getting the error
TypeError: 'builtin_function_or_method' object is not subscriptable
here is the code. https://pastebin.com/t1vGn6Yh
here is a traceback snip
well the problem is that you can't do g.user['id']. it's possible this should be g.user.id instead if user has an id attribute.
@white prawn you appear to be treating user as if it's a dictionary but my guess is that it's some sort of model?
and that error "is not subscriptable" always means you can't do [1] or ["something"] on that type of object
might be good to commit to memory, you'll probably see it again
so shall i just try using g.user.id? istead of doing g.user['id']
here is the auth that deals with user part
I am trying to follow the tutorial but not sure what I am doing wrong .. I have added more fields to just test out if that would work @deep cave
aha, I think your problem is on line 71
fetchone should be fetchone()
right now you're setting user equal to the fetchone method itself
you want to set it equal to its return data
in which case your user['id'] is probably correct
@white prawn
@deep cave thanks that resolved it out
good! happy to help.
How would you suggest i should test whatever imade?
is there a good guide to do tests ?
you mean like writing automated tests or just testing it as a user?
I am actually trying to learn the webdevelopment with flask along with doing tests.
I am not sure what is much used in industry
Also i want to brush up the python more, would be great if you could point me to the right direction π
The Resources page on our website contains a list of hand-selected goodies that we regularly recommend to both beginners and experts.
and consider using a linter like flake8, or at least an editor or IDE that has some basic linting features built in. pycharm is pretty good.
the code you showed so far doesn't look too bad, though.
pycharm is paid actually i have been using vscode
pycharm has a fully featured free edition
the community edition
but vscode is also pretty good - at least with the right plugins
I had got a bunch of crazy plugins have been looking for good plugins being a beginner with flask and django and intermediate with python
ask in #tools-and-devops, lots of people on this server use vscode
I'm not one of them, though
pycharm addict here. can barely code without it. it's just so goooood.
I will go for pycharm but my machine is pretty old.. might hang haha
that is a legitimate concern
pycharm is a resource hog
some users with older laptops can't really run it at all, at least not with acceptable performance
and in those cases, vscode is a better choice for sure
also any tips on best way to retain the knowledge i gain by doing, cos i tend to forget at times
keep notes?
I like physical notes. although OneNote is pretty good if you're on windows. Zim is okay if you're on nix, but I prefer a private git repo on gitlab full of markdown files
could you give me an example of how you actually keep notes, a pattern or a technique. Would help me to kick start
I write little guides for myself, often.
just curious as what those guides contains
typically I write shit like this when I'm at work.
and then it doubles as useful documentation if a colleague runs into the same problem
I don't have any python-related notes handy, those are mostly in actual notebooks
it's a while since I was learning python
I also use highlighter pens a lot when I read textbooks
and then go through them and look at my highlights to refresh my memory later
do you have any specific book you would personally recommend as I am almost an intermediate to python but won't mind if it covers things from beginner to advance level
as an intermediate, I might recommend Effective Python and Fluent Python
intermediate books that teach best practices and advanced features.
very very good books
and preferably in that order
do they also cover the beginner aspects too?
not really, no
so for beginners what would be your suggestion?
for a beginner I'd mention stuff like Automate The Boring Stuff With Python for absolute beginners who wanna start doing something useful, or possibly A Byte of Python for you if you've already got some programming experience under your belt.
i liked that book automate boring stuff with python helped me clear the regex part that i always got stucked wit.
you've already worked through it?
i left it in between lol
well, you know basic syntax, right?
got a project to work with hence had to switch... to flask for that small project...didn't got back to it
yes.
and the basic building blocks of programming - conditions, loops, functions, maybe objects and inheritance?
then you should just be doing projects.
until you get the rest of those down, imo.
flask is good
miguel grinsberg has a great flask book - and also a free mega-tutorial that teaches flask.
and Corey Schafer on youtube has a video series on it
dive into flask. you'll pick up other python tricks there.
and pick up that Effective Python book. it'll probably be very useful - possibly a bit confusing around the middle but you should be able to get lots of value from it and you can come back to it later.
same with fluent, tbh it's a big fat reference-book sized tome, but it's very thorough.
so first i shall go to fluent then effective or other way around?
aha
50-ish microchapters with good tips for being a better python programmer, basically.
also should i revisit automate boring stuff with python once before starting with fluent >
if you want to. lots of useful practical application stuff there
the other books are more theoretical
reason is I was not able to finish that book at all
so i am thinking to read thru it again and than move to fluent
however about projects.. i am bit confused as what shall i make? I don't have a list or so
or any idea what projects shall i do
how in django do i go about responding to <form id="LogInForm" method="post" action="CALL FUNCTION HERE"> something like this with arguments passed
or basically just call a backend function
how would you run a python function when someone presses a button in flask? I know there is the POST thing but that seems very limiting as to my knowlage, there can only be one button per page
@steel tiger i think you would add the url that relates to the function to the action attribute
in a html <form action="/do_something"> <button type="submit"></button> </form> or directly on a html <button action="/do_something"></button>?
im not too familiar with flask, have you heard of the url_for thing before? @steel tiger
Variable arguments that are unknown to the target endpoint are appended to the generated URL as query arguments. If the value of a query argument is None, the whole pair is skipped. In case blueprints are active you can shortcut references to the same blueprint by prefixing the local endpoint with a dot (.).```
i kindof have now
Β―_(γ)_/Β―
what shall i use for web applications? django or flask
your choice
anyone experienced with flask here?
A handful. What's your question?
one sec
basically I copied this discord oauth example: https://github.com/discordapp/discord-oauth2-example/blob/master/app.py and turned that into a blueprint so my app is more organized
however, I now get RuntimeError: The session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret.
when I try to set the secret key where the app is created, it doesn't change anything
oops nevermind, I saved it in the wrong file π€¦
sorry
Hey guys! I finally got a flask server running. Now how do I start accepting API calls? I assume different defs...?
All I want is to send and recieve files to this HTTP File server I have.
lemon said you guys could help rom here.
The server is digiduncan.com:5000
@sonic steeple Is also helping with this
Is there a way to get gevent.wsgi to handle more than one requests at a time?
nvm i just had to monkey patch it
can someone tell good sources to learn django
have already learned a little from djangogirls and udemy
Hi I have a python script that returns values from a api in a json file is there a way I can get the values to be displayed on FLASK?
import json
r = requests.get('https://openexchangerates.org/api/latest.json?app_id=USERKEY')
data = r.json()
gbp = data["rates"]["GBP"]
eur = data["rates"]["EUR"]
print('GBP', gbp)
print('EUR', eur)```This is the script any way I can use it in FLASK?
@minor zenith Two Scoops Of Django is a good book that hits a sweet spot between beginner and intermediate. Itβs well written and the two authors really know their stuff.
thanks already bought that π
@minor zenith Corey Schafer on YouTube has a great series on Django, too
thanks π
Would anyone want a free url? I have a few that I got for free and dont want or need. They expire next october, and I will do nothing with them. I'll transfer it to you and that's it. You owe me nothing.
They are dumb names
But they are free
ludum.live
ludum.press
and ludum.host (taken now)
dm me and they are yours
(I posted here because it's web dev, but I apologize if it shouldn't go here. I'll remove the offer if im breaking a rule)
it's fine, you're just giving stuff away. I got no problem with that
okay thanks
@deep cave except in 4 discords no one has accepted
they think I'm scamming I think
but how could it be?
maybe they just don't like your domains
to be fair a .press domain is what, a buck or two?
I figure anyone who has something to point it at will also be able to pay a buck for a domain that actually fits their site.
@wanton wharf still got one of them to sell?
yes
I'll have please
nvm
ludum.press and ludum.host are still available
sharpie said he was good after all
In Flask I have a main route for serving web requests and a Blueprint for displaying the admin dashboard.
I'm having an issue where the blueprint does not switch from admin back to main when I access a non admin route
the only way to correct the behavior is to save the run.py file used to power the app
i'm working on my Flask app at the moment. just ask and someone will respond @native tide
has anyone in here worked with proxys and python
yes
is it safe to raise a 404 before raising permisison denied? E.g. in django:
@login_required
...
# if object wasn't found:
raise 404 error
# if object.user != request.user:
raise PermissionDenied
think in this case where any given note is private and only accesible by one user.
website.com/notes/1/
website.com/notes/2/
Say user A can access note 1, and user B can access note 2.
when A tries to access 2, they get a permission denied error.
when A tries to access 3, they get a 404 because note 3 doesn't exist. now user A knows that the URL .com/notes/2 is in fact a note, but they get a permission denied error when they try to access it.
the url doesn't reveal anything about the note, so there's nothing wrong with designing a website like this right?
why are you pinging a bunch of people.
don't do that
and that question is big, you should do some reading first. a selector is, for example, div.bigbox#inputbox. it's how CSS selects specific elements in the DOM.
read up on it, come to us if you have more specific questions.
!warn @verbal panther don't ping a bunch of people when you ask a question
:ok_hand: warned @verbal panther (don't ping a bunch of people when you ask a question).
no idea what you're asking
@ornate coral yeah
if it doesnt reveal anything about the note, then its fine
knowing that a specific url is a note isnt very useful if theres no info
Ok π thank you
Does selenium questions go here?
yes?
still here?
Making my own website but i cant seem to get to change the webpage icon from a File icon to an icon of my choosing
Hi, i'm writing a Flask app which serves images, although I am unsure how i should store the images. I'm thinking a google cloud storage bucket, but i'm not sure how that would work. what would you guys reccomend?
a normal SQL database works fairly well. blobs in postgres, for example.
google cloud is probably more scalable if you need a bajillion images
well, you still benefit from the bucket storages. if you store it in the blob in your database that would mean that all the traffic would go through your service
if you store in on a cloud bucket you can generate temporary links and just respond with 303 and location header to redirect client to the cloud
in this case the response time from your api would be super quick, and you won't have to scale it just because of the traffic is creating additional response time
and with the cloud buckets you also benefit from their CDNs, which would guarantee fast access to your images from all over the world.
hey, I'm making an API which is supposed to
1- Accept Files
2- Compress and store files according to the IDs I give
3- Return a download URL which can be used later if people want to download files
The API is on python while the Front is on VueJS
I need suggestions on-
1- Where should I store the file
2- How to make a system so that Scrappers can't take away all the file dowload links
3- Is accepting files over POST req a good way, if not, what is the alternative, considering max file size <= 100MB and average is around 10MB
hey prince, how about media storage to save the files on s3 or digital ocean spaces? No clue about the rest, sorry
Hey guys, I need to choose between abstract and generic django class inheritance and wonder about your experience and how you have solved this in the past: https://stackoverflow.com/questions/53301302/abstract-or-generic-django-class-inheritance
Best way to store files?
of your computer? of a website? what kind of files? photos? plaintext? videos? other media? store how long? indefinitely? how many files?
OOh, sorry, I just forgot I wrote this here. My bad!
I am making a file repository kind of thing, basically people come and upload or download files. Max file size < 50MB, average size <3MB. I am using flask
Where and how should I store these files and how do I give download access as well
I am looking into Dropbox right now, but is there something better?
Or a better way to do it?
Files can be PPTs PDFs DOCX XLSX
Anybody have any web app ideas/business ideas/side projects they are working on that need another dev? I'm stuck in an "idea block" and I have no side projects / main projects to work on right now
@twin thunder whats the point in a file repository that just sits on top of dropbox
why not just use dropbox
Hey guys how can I make my flask website public, I port forwarded but and it works for other devices only on my network, how can I make it so anyone around the world can access it?
How did you setup the port forward?
How are you testing external accessibility?
also remember that flask recommends you do NOT use the flask server itself as a host on the internet


