#web-development

2 messages ยท Page 5 of 1

meager anchor
#

magic โœจ

grand badge
#

when i did self.model.slug i had no idea what i was doing xd

meager anchor
#

are you sure that that's the actual slug of the current object and not the field of the model?

grand badge
#

let me check

#

yep

meager anchor
#

alright

brave mantle
gleaming drift
#

Could someone at least point me in the right direction?

grand badge
#

What do you mean @gleaming drift ?

gleaming drift
#

I can copy paste see 2:43 (that's PST time) so roughly 6 hours ago

#

right before your and gdude's convo I believe

#

tbh I didn't know where to ask, figured since my program is in python this be a starting point

#

lol were they giving me shit cause my question was bad? I just noticed that

grand badge
#

umm

#

i dont think many people use nodejs in this server. I mean its a server dedicated to python

gleaming drift
#

right, i'll use python if possible

#

problem is idk what exactly im lookginf for

#

just dont want to sign into game, join match every time I wanna work on prog

grand badge
#

U can stick to your node.js thing, but you have to find the right place to ask the question

#

Do u know the Programming server?

gleaming drift
#

can i use python to just send the json to myself at set intervals

#

what you mean prog server?

#

actually, im sure i can, just thought of that

grand badge
#

im not familiar with JSON

#

I guess u can lol

gleaming drift
#

1 min ima check something really quick

#

plz

indigo holly
#

Is there a way to render templates with place holders. In example I have 50 pages for every state but don't want to write 50 routes. Just one where the url is index/[state]. Below is the code I wrote thinking it would work but got a template not found error.

from flask import Flask, request, render_template

app = Flask(__name__)

@app.route("/index/<state>")
def state_page(state):
    return render_template('state.html', state=state)

if __name__ == "__main__":
    app.run(debug=True)
grand badge
#

did u put the html template in templates directory? @indigo holly

meager anchor
#

@indigo holly maybe it'd be better to have state passed as a GET parameter and then passing it to the template as context?

indigo holly
#

It is in the template directory! And one second Volcyy. Let me see if I can translate that to code with what you suggested.

#

So @meager anchor I'm not sure how to make this code into a placeholder that can be dynamic. I understand how routes work statically though.


app = Flask(__name__)

@app.route("/state", methods=['GET'])
def state_page(state):
    return render_template('state.html', state=state)

if __name__ == "__main__":
    app.run(debug=True)
meager anchor
#

one sec

#

ok, so you want to access the GET parameters from the request

#

a quick glance over the docs tells me you can access the request using from flask import request, and then get arguments from it using request.args.get('key', '')

#

so in your case it would be

#
from flask import request  # and your other stuff

@app.route("/state", methods=['GET'])
def state_page():
    state = request.args.get('state', default)  # set default to whatever the default state should be
    return render_template('state.html', state=state)

# ...
#

then you can use state in your template

west glen
#

You'd want to change your @app.route to just be a catchall in this case, no?

meager anchor
#

wdym?

west glen
meager anchor
#

oh, yeah

indigo holly
#

Richy, you're correct about the example.com/VA my original example just included an additional slash for ... not sure

meager anchor
#

I think initially it was /index/VA

#

what I'm suggesting is /state?state=x

indigo holly
meager anchor
#

Hm

#

Well, GET parameters would all be on a single route

indigo holly
#

Sorry about the confusion here

west glen
#

I think your original code might have been correct,.
Can you try creating a static route that you know works, then retry using the template on that route. That'd help you diagnose the "template not found error".

indigo holly
#

Sure. Be back soon with results

brave mantle
#

@indigo holly Try enabling flask debug mode

#

That'll help you figure out errors like that

#

As for your first block of code, that approach was fine

#

The error was just that it couldn't find the template

indigo holly
#

Hm. Okay. So it's a pathing issue?

#

Because when I type example.com/FL I want it to open my FL.html but so I was trying to make the code replace 'state' with the string of the url entered.

#

Let me try the directory stuff again

west glen
#

If you have it stored in FL.html, that's the issue, it's looking for a file called state.html.
You'd need to a string replacement,
either
'{}.html'.format(state) or f"{state}.html"

#

But with templating, you should be able to create that state.html file, which takes the name of the state, and any of the information, and renders out the html from there.

#

@indigo holly , incase you're busy working, not reading Discord ๐Ÿ˜› ^

indigo holly
#

๐Ÿ˜ฌ

meager anchor
#

I think the string formatting method could work, but isn't it dangerous as a user could try to access example.com/../../someotherfile and break the app?

west glen
#

They could, yes, so you'd want to check the state is in a collection of supported states, and send them a 404 otherwise

brave mantle
#

No they couldn't

#

Not unless the param uses the path type

#

Which I don't think it does

#

Without the path type set it will ignore anything after the slash

#

Including the slash actually

west glen
#

Oh, I see, you were using .., I read that as ...

indigo holly
#

Alright, I think I have a better grasp of what to do here. Thank you for the helpful assistance everyone

west glen
#

If you have a seperate, manually created page for each state, the render template is probably not what you want, but hopefully you'll crack this nut

indigo holly
#

The HTML guys and supervisor change what they want everyday, so we'll see haha

meager anchor
#

Getting Postgres to work with Django tests is insanely frustrating

#

Yesterday I first had an issue with Django apparently truncating (pgsql) passwords longer than 70 characters, now when setting it up locally, I keep getting "relation does not exist" when trying to create a test database

#

Then, it keeps trying to delete and recreate the test database, which makes permission management very weird

#

If I tell it to not delete it, it will just not run any tests. If I tell it to (and I even made the pgsql user that django uses superuser for testing), I get ```py
psycopg2.ProgrammingError: relation "audit_log" does not exist
LINE 1: ..."audit_log"."reason", "audit_log"."category" FROM "audit_log..."
^

...

During handling of the above exception, another exception occurred:

...

cursor.close()
psycopg2.OperationalError: cursor "_django_curs_140735985812352_1" does not exist

which I don't understand. We had the same issue on the actual database yesterday but I don't know what fixed it
#

Did anyone run into similar issues?

#

I mean, I can just test against the actual remote PGSQL database (on a test database, of course), but that's a lot slower than running it locally and also kinda besides the point

#

For the record, I'd like to stay away from Docker for running this.

meager anchor
#

OK, I think I figured it out. I don't know what caused the above issue, but one of the migrations was wrong and didn't create a column properly. No, it was not audit_log.

grand badge
#

I am trying to find a way to style a generic form in Django, I have looked online and have not found anything useful to help me style the generic forms.

# views.py
class TutorialCreate(CreateView):
    model = Tutorial
    fields = ['name', 'subject', 'description', 'content']

#
    <div class="">
        <form method="POST">
            {{ form.as_p }}
            <input type="submit" value="Create Tutorial" class="btn btn-primary">
            {% csrf_token %}
        </form>
    </div>
#

i think i have to add custom css

#

fixed it

#

i just had to add some CSS

label{
    display: block;
}
little nexus
#

is it possible to use dash (https://plot.ly/products/dash/) with django? how can i use dash for just 1 page on my site, if it starts its own webserver?

little nexus
#

anyone?

#

also what are the main differences between django and flask

grand badge
#

django is like a "batteries included framework"

#

flask is a "batteries not included, buy them" framework

#

django makes u do stuff the "django" way

#

flask lets u do stuff your way

tame viper
#

that's a decent analogy

grand badge
#

but u can build the same stuff with both frameworks

strange thorn
#

django users are weird people to me

little nexus
#

ok, i think im getting this

#

and what do you reccomend to deploy my site? it says that the flask built in server isnt suitable for production

strange thorn
#

easy to use would be gunicorn

little nexus
#

that is what i found

strange thorn
#

yup

#

use that

#

its fine

little nexus
#

with ngnix?

strange thorn
#

no no

brave mantle
#

We use gunicorn in production here, behind nginx

#

yes, you need nginx.

strange thorn
#

you can use gunicorn standalone

#

cant you?

brave mantle
#

You shouldn't, but yes

little nexus
#

yeah but i might be seeing a lot of load on my server

brave mantle
#

you should have nginx serve your static files directly, and then proxy everything else to one of your gunicorn workers

meager anchor
#

iirc you proxy it to the master and that one handles routing to the workers

strange thorn
#

nah unlikely you see that much load

little nexus
#

probably not but it might go big who knows XD

meager anchor
#

I think gunicorn recommends cpu_count * 2 + 1 workers?

brave mantle
#

Yeah

little nexus
#

yeah thats what i saw volcyy

brave mantle
#

We also use gevent here

#

Which helps a lot

little nexus
#

what does gevent do

strange thorn
#

its like asyncio

brave mantle
#

It makes a bunch of things asynchronous under the hood

#

It's pretty much transparent though

little nexus
#

ahh

brave mantle
#

gunicorn has explicit support for it

strange thorn
#

and in case that isnt enough

#

you can still split your stuff up to multiple machines/vms/containers and put for example ngnix as a load balancer infront

brave mantle
#

You'd probably want to use squid

#

but yeah

little nexus
#

haha dont think ill ever get that much load

#

but yeah, good to see expansion options

strange thorn
#

scaling is so important these days

brave mantle
#

the point is that it's not super hard to do

#

gunicorn scales well

strange thorn
#

well not anymore

#

it used to

brave mantle
#

OK, but most of us don't live in the past Nix

#

:P

little nexus
#

also i saw a lot about running things in isolated python containers? what is all that about?

brave mantle
#

Docker

strange thorn
#

docker

brave mantle
#

yeah, you can do that, it does make automatic deployment easier

strange thorn
#

well there are others

brave mantle
#

We also do that

strange thorn
#

but most lkely docker

#

9.9/10 docker

brave mantle
#

well I mean you'll be using docker or LXC

#

and docker is basically just an API on top of LXC, if you're on linux, so

little nexus
#

what does docker do?

brave mantle
#

It's a very light virtualisation layer

#

You're basically running your application in a very small VM

#

All it does is keep its networking and resources separate from the rest of your machine

strange thorn
#

basically it runs another system which still uses the same kernel as the real system but everything else is virtualized

little nexus
#

ok

strange thorn
#

think of it as a cool version of virtual machines

little nexus
#

which bits would you put in a docker instance then?

brave mantle
#

Gunicorn and your webapp itself

native tide
#

u can use virtualenv in place of docker

strange thorn
#

no

native tide
#

i do that only

brave mantle
#

No you cannot

strange thorn
#

thats bullshit

brave mantle
#

they are completely different things

native tide
#

how?

strange thorn
#

virtualenv is completely different from docker

#

they arent related in any way

native tide
#

they r different

strange thorn
#

not even close to

little nexus
#

what does virtualenv do then

brave mantle
#

They do different jobs, you can't replace one with the other

#

that's a silly assertion

strange thorn
#

it isolates you rdependecies

#

from the main system

brave mantle
#

yeah, that's basically it

native tide
#

yeah

strange thorn
#

but everything still runs on the main system

little nexus
#

why would isolating them be good?

strange thorn
#

yes mostly

#

we use pipenv for this

brave mantle
#

When you have more than one python application on a single machine, their dependencies can overlap and conflict

strange thorn
#

its like virtualenv + pip

brave mantle
#

virtualenvs solve this problem

little nexus
#

ahh

#

right i see

strange thorn
#

but docker

#

nearly runs a completely different machine

native tide
#

ohh

brave mantle
#

docker goes one step further and isolates the entire running environment basically

strange thorn
#

its no related to virtualenv

little nexus
#

would you run a virtualenv inside docker then?

brave mantle
#

You could do

#

you don't need to though

#

it's already isolated

little nexus
#

but there isnt much point?

#

yeah ok

strange thorn
#

yes but due to most docker containers only being used for one thing it wouldnt make sense

brave mantle
#

docker containers can actually only be used for one thing

#

that's the point

strange thorn
#

it only makes sense if you have multiple things running on the system

#

like for example

#

2 flask apps which need different flask versions cause one cant use a higher one

#

in this case the one which cant use the higher version would break

brave mantle
#

I think he gets it, nix

#

:P

little nexus
#

yeah, mostly

strange thorn
#

mkay

#

walks off

little nexus
#

good good

#

:P

#

thanks for the help guys

#

why would you want to use docker? to run multiple websites behind an ngnix server, on one (or more) servers?

strange thorn
#

lets say 1 instance of your web app cant handle the load

#

you just run 2 put them behind a load balancer and bam it can handle the load

#

and docker is used for running those two

little nexus
#

and what would be docker's job there?

strange thorn
#

with docker you can run 2 seperated environments on the same machine

little nexus
#

but why 2 seperated and not 1 big one?

#

assuming compatability of deps is not an issue

strange thorn
#

paralelism

#

look at for example super computers, why dont we just build one mega CPU and instead have dozens of computers running at the same time

#

so they can handle a LOT different tasks at the same time

little nexus
#

right

strange thorn
#

while one big one may handle a small amount faster 2 normal ones can handle more at the same time

#

(at least thats my understanding)

little nexus
#

so an open connection might block a webserver so your second instance can take another connection smoothly? am i kinda close here?

strange thorn
#

yes

little nexus
#

right

#

i think i get it now

#

the same kinda reason cpus have more than 1 core

strange thorn
#

and what the load balancer does is just counting who has who many connections to handle and splits them up according to that

#

and yes thats exactly what i was meaning with the super computer example

little nexus
#

right

#

and the "tree" for everything would be in this order? ngnix -> docker -> gunicorn + flask

strange thorn
#

yes you can do it like that

little nexus
#

is there a better way?

strange thorn
#

you could split it up to several physical machines too and run docker containers on all of them

#

but on the software level apart from maybe using some container orchestration software this is a very good way to scale the app

little nexus
#

ok, i think ive got it

#

thanks

brave mantle
#

eh

#

what Nix says isn't very clear

#

Docker has this thing called swarming

#

so you set up a bunch of machines in your docker swarm

#

and then you can use - for example - saltstack or docker itself to deploy containers to the machines in the swarm

twin shoal
#

Not sure if this is the right channel but how would I go about using HTML to open a python script and run it?

#

Like if I were to click a button and it would launch a python script on my computer

#

(without flask or any similar programs)

brave mantle
#

You can't do that.

#

There is no way to do that, and that is deliberate

strange thorn
#

well he could use electron and some js.....

twin shoal
#

@strange thorn How would I do it then

strange thorn
#

oh you dont want to do that

#

its an ugly and overkill solution

brave mantle
#

You can't do it from a website

#

Which is what he wants

strange thorn
#

yeah thats true

twin shoal
#

Would it be possible to use PHP and exec the py script?

strange thorn
#

why do you even want that

#

you can use python to exec py script

twin shoal
#

...

#

I'm working on a small web gui for myself that would run different py scripts

strange thorn
#

you uh

#

do realize you can use html js and python all together to make webapps

twin shoal
#

oh how so

strange thorn
#

well

#

python is pretty popular in doing the job php usually does

#

you can use a python webframe work like flask or django (django seems a bit overkill for this) to do what php usually does

#

and then just use normal html and js at the frontend

twin shoal
#

oh flask

brittle copper
#

Not sure if this is the right channel but how would I go about using HTML to open a python script and run it?

#

That would be a huge violation of your security lol

#

No one would ever visit your site if you can achieve it which you never will

fast fable
#

Hi all, I just read posts. @twin shoal Web GUIs have these pillars: HTML, JavaScript and CSS and you cannot run python in your browser. Browser simply does not understand python.

#

But you can serve points to call from your web gui to accomplish what you want

twin shoal
#

thank you, but I ended up just using django ๐Ÿ˜›

fast fable
#

Cool. I would had recommend flask ๐Ÿ˜‰

twin shoal
#

haha at first I didn't really want to try django cause I had no clue what I was doing but spent some time on the internet and now it's all good

fast fable
#

nice!okhandbutflipped

tame viper
#

awesome, you've gotten further than i have and i've actually tried :D

grand badge
#

I am trying to make a search bar in django using Class Based Views. However, the code i wrote always raises a KeyError when i type something into the search bar. I have looked online and couldn't find anything useful


class TutorialSearch(ListView):
    model = Tutorial

    template_name = 'tutorials/tutorial_search.html'

    def get_queryset(self):
        term = self.kwargs['term']
        if not term:
            return self.model.objects.none()
        else:
            return self.model.objects.filter(name__icontains=term)


the error that is raised from this is:

    'term'
grand badge
#

nvm i switched that view back to FBV

stone pelican
#

What's the error?

#

Ops

#

Didn't scroll down enough

tame viper
#

@grand badge is it because there's not 'term' key in whatever kwargs you've got?

grand badge
#

no

#

but nvm, i fixed it, well not the way i wanted to

#

but its fixed

tame viper
#

fair enough

grand badge
#

i just took the view back from CBV to FBV

meager anchor
#

Ok, so I'm working on user profiles for my site (Django). Currently profile URLs are profile/{user-id}, which works, but the URL is pretty ugly. I want to give users the ability to set "nicks" on their profile so they can access their profile using a simpler URL, e.g. profile/~volcyy. What's the best way to accomplish this without a redirect?

#

The redirect was my initial idea. Have an extra view handling profiles/~<str:nick>, if exists, redirect, else 404

#

But that would just change the URL back again and kinda ruin the point IMHO

tame viper
#

well

#

nobody cares about what a URL looks like

#

it's more about accessibility

#

i think a redirect would work fine

meager anchor
#

hmm

brittle copper
#

I wrote incredibly shity code just to have my pages ?page instad of /page

meager anchor
#

show

brittle copper
#

Hold on

#
page = request.GET.get('page')
if page is None:
    prev_opt0 = [1]
    prev_opt = prev_opt0[:-1]
    next_opt = [x + 1 for x in range(1, int(paginator.num_pages))]
    page = 1
    nexty = int(page) + 1
    prev = int(page) - 1
else:
    try:
        if int(page) > paginator.num_pages:
            page = paginator.num_pages
    except ValueError:
        pass
    try:
        prev_opt0 = [x + 1 for x in range(int(page))]
        prev_opt = prev_opt0[:-1]
        next_opt = [x + 1 for x in range(int(page), int(paginator.num_pages))]
        nexty = int(page) + 1
        prev = int(page) - 1
    except ValueError:
        prev_opt0 = [1]
        prev_opt = prev_opt0[:-1]
        next_opt = [x + 1 for x in range(1, int(paginator.num_pages))]
        page = 1
        nexty = int(page) + 1
        prev = int(page) - 1
try:
    mtitles = paginator.page(page)
except PageNotAnInteger:
    mtitles = paginator.page(1)
except EmptyPage:
    mtitles = paginator.page(paginator.num_pages)```
#

Yeah I do realize how bad this is

#

But it was my very first project ever

#

I directly jumped into django without even knowing what even a class was

#

Also half of these should be javascript instead of python, lol

meager anchor
#

what

#

i'm very sure that Paginator handles all of this by itself

#

literally all I had to do to add Paginator to my generic.ListView was adding ```py
paginate_by = 10

and some simple html
```django
 {% if is_paginated %}
    <nav class="pagination align-center">
      <ul>
        {% if page_obj.has_previous %}
          <li><a href="?page={{ page_obj.previous_page_number }}"><</a></li>
        {% endif %}
        <li>
          <a href="#">Page <strong>{{ page_obj.number }}</strong> of <strong>{{ page_obj.paginator.num_pages }}</strong></a>
        </li>
        {% if page_obj.has_next %}
          <li><a href="?page={{ page_obj.next_page_number }}">></a></li>
        {% endif %}
      </ul>
    </nav>
  {% endif %}```
brittle copper
#

Yeah it adds previous_page

#

But doesn't add all previous pages does it

meager anchor
#

you mean in the HTML?

brittle copper
#

Hold on lemme show it

#

I made this whole thing work with python instead of using couple of lines of javascript

#

And I do realize the python code is also disgusting

#

But hey, I didn't know python at all when I started it sooo /shrug

meager anchor
#

this looks like you could accomplish it in the template with a for loop easily

brittle copper
#

I mean there are a lot of eaiser, better, cleaner ways to do it

#

But I used to suck

idle steppe
#

anyone here know how did they manage to design this ?

grand badge
#

uhhh

#

a lot of image tags?

#

maybe one image tag

#

no

#

prolly no image tags

#

and just a background in css

#

too much bad pics

kind steppe
#

no that looks like seperate images

#

I'd say that is image tags

#

with css to say don't wrap to a newline after every image

grand badge
#

ahh yes

#

i saw that channel move

kind steppe
#

wait what

#

oh it wasn't me

grand badge
#

it was ap

idle steppe
#

they are saparate html element each image is hyberlink

#

they are dynamic each time you load the page u get different images in different position and sizes

brave mantle
#

it's a flexbox layout

idle steppe
#

flexbox only overlap colums or rows but this oberlap both !

#

overlap

indigo holly
#

Doing my first web app deployment and using python anywhere. Anyone famliar with why I'm getting an error
"RoundBallmain.app as application imported but unused" Here is the relevant code:

import sys

# add your project directory to the sys.path
project_home = u'/home/my-path/RoundBallAnalytics/project/'
if project_home not in sys.path:
    sys.path = [project_home] + sys.path

# import flask app but need to call it "application" for WSGI to work
from RoundBallmain import app as application  # noqa

I followed the tutorial through their documentation and pulled everything from my Git files.

Locally, everything works fine however right now the site has some pages that show and others that give errors.

indigo holly
#

So I think my git clone downloaded all my files but older versions of them. This may be the issue. Not sure why github did that

dry portal
#

Sup everyone, got a Flask question here.

#

I'm working on an OAuth workflow via a website for my Discord bot, and it just makes sense to make all the API calls after the authentication from within the website script instead of having the Discord bot do it for avoiding issues later on. Now, these API calls in total can take roughly 5-10 seconds, and I'd like to render an HTML basically saying "Hold up, this can take a few seconds", then rendering another saying it succeeded at the end. Using render_template at the top of the app route doesn't work though (I'm very new to web development). Anyone have any ideas on how to do it?

brave mantle
#

Ok, so you have a long-running task

#

there's a couple ways to do this

#
  1. Set up a task runner (eg, Celery), farm out your tasks to that, and use AJAX to query the status of the task (securely)
#
  1. Set up a task runner and use websockets to communicate task status between the server and the browser
#

either way, you can't just render and render again, you'll need some logic on the page to make the client reload or move to another page

#

that means javascript.

dry portal
#

Gotcha. There's no way to render and after the render run more scripts, right?

brave mantle
#

No, the reason for that is just how the lifecycle of a request works

#

No data is returned to the client until the request function has finished executing

dry portal
#

Ahh, that makes sense. I know literally 0 JS, so this is gonna be fun. ๐Ÿ˜›

#

Well, thanks man, appreciate it!

brave mantle
#

No worries

deep cave
#

don't listen to the haters. JS is nice.

dry portal
#

DAX Master Race ๐Ÿ˜›

#

Completely useless for coding but it's how I learned the basic stuff (in Excel, lol)

tame viper
#

i've heard that it's possible to host a website on a raspberry pi, but i don't know how possible or advisable that is, especially for someone like me with very limited knowledge in this field. thoughts?

neat nest
#

reasons to do it:
(1) very good learning experience
(2) you don't have to pay for anything you're not already paying for (except possibly a domain)

things to be taken into account:
(1) you need to obtain a static IP address
(2) you are more actively exposing your private network to you internet when asking people to come take a look at a website hosted on it. this shouldn't be a strong determent but be very security conscious
(3) you're probably not going to be able to field terribly heavy traffic

tame viper
#

the learning experience is my main focus, by far.

grand badge
#

Raspberry pi i guess is okay for hosting

tame viper
#

and as i only plan to make a simple personal blog sorta thing, i don't think resources would be an issue

grand badge
#

Have u heard of pythonanywhere?

tame viper
#

oh, i really dislike that.

grand badge
#

Its gud for beginners

tame viper
#

but as a beginner, i want to learn all that i can

grand badge
#

ah

tame viper
#

also, i prefer to have everything where i can see it. yes, i'm that sort of person.

#

i get paranoid when i don't do stuff myself

#

(also the reason why i don't trust UUID haha)

grand badge
#

hav u heard of heroku, linode or digitalocean before?

tame viper
#

yes, but the same goes

#

i want to be able to manage it all myself

grand badge
#

Ah k

tame viper
#

and stuff like that

neat nest
#

don't know much about linode, but your experience with digiocean is bound to be almost identical to your raspberry pi experience, just remote

grand badge
#

So u gnna use raspberry pi to host?

neat nest
#

oh wait actually I guess some people in the world use guis

tame viper
#

nah i don't have a GUI on my pi

neat nest
#

all the server work would be very similar, then, digiocean would just handle the whole "having a network" bit

tame viper
#

but you see, i don't know what the fuck goes on with "having a network"

neat nest
#

fair point

native tide
#

is digiocean an abbreviation?

neat nest
#

yes that's what I call it

native tide
#

o lmao

tame viper
#

because the tal is so hard to type

neat nest
#

I'll fight anyone that questions me ๐Ÿ”ซ

#

I'm on a phone

grand badge
#

Why u do dis?

neat nest
#

every curve of my swipe counts

grand badge
#

Why u say digimon?

tame viper
#

ew

#

swipe

#

:^)

neat nest
grand badge
#

k

tame viper
#

i'm in.

meager anchor
#

i also thought about hosting my website on my rpi, but as lucy said that would mean exposing my private network and I'm not a big fan of that

#

it's great for other projects though, right now i have pihole running on it and, uh, well that's about it GWfroggyBlobThonk

#

but yeah basically, you should look into a digitalocean VPS, if you're a student you can get a $50 starting credit

#

to me there's like no difference between using the VPS and the raspberry pi, both are debian derivatives ๐Ÿ˜› so yeah, i'd recommend that. it's also a good learning experience

brave mantle
#

My pi runs arch :>

whole robin
#

@brave mantle same

#

arch works well on rpi, also because I refuse to use any other os other then arch ๐Ÿ˜†

kind steppe
#

Pi behind cloudflare

#

sortedโ„ข

#

no exposeโ„ข

brave mantle
#

I used to have a pi-hole but they're kinda slow

#

Might set it up again if I end up with an actual machine for a server

meager anchor
#

They rewrote parts of it in C recently, IIRC

indigo holly
#

Anyone familiar with dynamic routes in flask?
If I have a bunch of HTML files for separate pages is there a better way to route to them with less code than an IF statement for each one, like this:

@app.route('/<page>')
def index(page):
  if page=='example1':
     return render_template('example1.html')
  if page=='example2':
     return render_template('example2.html')
tame viper
#

i don't know much about flask, but could you not use a dictionary?

#

like

indigo holly
#

That's what I was thinking actually

tame viper
#
{
    "example1": "example1.html",
    ...
}
mild bridge
#

will the html page always have the same name as the page variable?

#

e.g. index(x) would return x.html?

indigo holly
#

No its based off US states. so the URL preferably be

url.com/fl  returns florida.html
mild bridge
#

ah

#

yeah, you'll probably need a dictionary

indigo holly
#

Alright that makes sense! Just wanted some reassurance before I started. Thanks all

indigo holly
#

I'm getting an error that I haven't been able to troubleshoot with the internet so far.
Error: render_template() argument after ** must be a mapping, not str

I understand what its saying that the render_template can only take one parameter but unsure what to pass then

state_page = {
    'fls':'florida_senate.html', 'vas':'virginia_senate.html', 'national':'national_congress.html'
}

@app.route('/<state_page>')
def index(state_page):
    return render_template(state_page, **state_page)
tame viper
#

i believe you should make your index argument named state_name then do render_template(state_page[state_name])?

brave mantle
#

yeah, you're clobbering the scope

#

you have two variables named state_page

indigo holly
#
@app.route('/<state_name>')
def index(state_name):
    return render_template(state_page[state_name])

This worked! Thank you.

tame viper
#

:D no problem

meager anchor
#

So for some reason my Django doesn't purge the database properly after each test case, and I get some incredibly weird behaviour because of that. Shouldn't TransactionTestCase isolate the test? I'm using it because the others don't support fixtures...

#

"A TransactionTestCase resets the database after the test runs by truncating all tables. A TransactionTestCase may call commit and rollback and observe the effects of these calls on the database.
A TestCase, on the other hand, does not truncate tables after a test. Instead, it encloses the test code in a database transaction that is rolled back at the end of the test. This guarantees that the rollback at the end of the test restores the database to its initial state."

#

what..

#

Ah. Yes, I'm quite the idiot.

vestal hinge
#

can anyone help with django rest api

meager anchor
#

yes, but don't ask to ask

sonic birch
#

ok

#

so im doing node.js and im developing an api backend

#

im generating "random" images

#

so

#

this is my json output:

{
"gay": "http://isabaseurl.com/gay/gay1,gay2.png",
"lesbians": "http://isabaseurl.com/lesbians/lesbian1,lesbian2.png",
"boobs": "http://isabaseurl.com/boobs/boob1,boob2.png",
"ass": "http://isabaseurl.com/ass/ass1,ass2.png",
"pussy": "http://isabaseurl.com/pussy/pussy1,pussy2.png",
"dick": "http://isabaseurl.com/dick/dick1,dick2.png",
"men": "http://isabaseurl.com/men/men1,men2.png",
"random": "http://isabaseurl.com/random/gay1,gay2,lesbian1,lesbian2,boob1,boob2,ass1,ass2,pussy1,pussy2,dick1,dick2,women1,women2,men1,men2.png"
}```

This shouldn't be happening. It should be only picking one element from a constant array of elements. Any idea why?
#
const gay = [`gay1`, `gay2`];
const lesbians = [`lesbian1`, `lesbian2`];
const boobs = [`boob1`,`boob2`];
const ass = [`ass1`,`ass2`];
const pussy = [`pussy1`,`pussy2`];
const dick = [`dick1`,`dick2`];
const women = [`women1`,`women2`];
const men = [`men1`, `men2`];
const random = [gay, lesbians, boobs, ass, pussy, dick, women, men];```
#

This is my constant arrays

#

its grabbing all of the elemets and inserting them

deep cave
sonic birch
#

sh

#

its just a practice thign

#

im just practicing lmao

#

i couldnt think of anything

#

so

brave mantle
#

Hey man, just practise in front of a mirror

#

alright, uhh

sonic birch
#

like

#

it serves the json alright

#

but

#

im just stuck on how to actually "choose" one subject

brave mantle
#

I mean, there isn't enough code here to really

#

help you

#

you've got some json and some arrays

#

and.. nothing in-between

sonic birch
#
const app = express();
const base_url = `http://isabaseurl.com`;

const gay = [`gay1`, `gay2`];
const lesbians = [`lesbian1`, `lesbian2`];
const boobs = [`boob1`,`boob2`];
const ass = [`ass1`,`ass2`];
const pussy = [`pussy1`,`pussy2`];
const dick = [`dick1`,`dick2`];
const women = [`women1`,`women2`];
const men = [`men1`, `men2`];
const random = [gay, lesbians, boobs, ass, pussy, dick, women, men];


app.use((request, response, next) => {
    console.log(request.headers)
    next()
})

app.use((request, response, next) => {
    request.gay = `${base_url}/gay/${gay}.png`;
    request.lesbians = `${base_url}/lesbians/${lesbians}.png`;
    request.boobs = `${base_url}/boobs/${boobs}.png`;
    request.ass = `${base_url}/ass/${ass}.png`;
    request.pussy = `${base_url}/pussy/${pussy}.png`;
    request.dick = `${base_url}/dick/${dick}.png`;
    request.women = `${base_url}/women/${women}.png`;
    request.men = `${base_url}/men/${men}.png`;
    request.random = `${base_url}/random/${random}.png`;
    next()
})

app.get('/', (request, response) => {
    response.json({
        gay: request.gay,
        lesbians: request.lesbians,
        boobs: request.boobs,
        ass: request.ass,
        pussy: request.pussy,
        dick: request.dick,
        men: request.men,
        random: request.random
    })
})
app.listen(80)```
brave mantle
#

it's like a nothing sandwich

#

yeah that's a really odd way to do that

#

Why add them to the request object?

#

Just put them right into the json call

sonic birch
#

idk; a tutorial told me to do that

#

lmao

kind steppe
#

bad tutorial

#

That won't work

sonic birch
#

so what do you suggest then

kind steppe
#

because you assign to a different variable in each of your routes

#

putting it all into the same route

sonic birch
#

just basically fuck it in the same place?

#
    response.json({
        gay: `template literal?`
    })```
kind steppe
#

no

brave mantle
#

you need to do a node tutorial

kind steppe
#

yeah

brave mantle
sonic birch
#

but

brave mantle
#

but this is a Python server, so I don't really have one for you

sonic birch
#

isnt javascript enough?

#

lmao

brave mantle
#

Not really

kind steppe
#

I see what you are trying to do, but the request in the app.use is a different request to the one in the / route

brave mantle
#

the standard library is different

sonic birch
#

tbh i dont really care about the efficiency

#

just want to try to solve the goddarn picking out

#

random

kind steppe
#

no it's not efficiency

#

it literally won't work lol

sonic birch
#

It works for me. .-.

kind steppe
#

that makes very little sense

sonic birch
#

like

#

it feeds back the json

#

just not the intended way

kind steppe
#

well

#

you need an array

sonic birch
#

which i thought i defined.

kind steppe
#

no you didn't

sonic birch
#

but its there

#

@mild bridge maybe instead of reacting, could you help? <3

kind steppe
#
const myarray = ["one", "two", "three"];
#

to get a random value from that

sonic birch
#

is ti the same as python?

#

...

kind steppe
#
var rand = myarray[Math.floor(Math.random() * myarray.length)];
sonic birch
#

im gonna scream if it si

#

cries in spanish

kind steppe
#

okay

#

cry quieter

sonic birch
#

when you think javascript already chose random ones for you from your previous code snippets

#

bc it literally did that for me

kind steppe
#

yes but putting random commas into a string doesn't tell javascript "hey i wanna get a random value lol"

sonic birch
#

fml lmao

#

so am i gonna have to add another 8 variables

#

to solve

kind steppe
#

no

#

you are going to add an array with the 8 values in.

#

and then add it to the base url meme

sonic birch
#

base url meme lmao

kind steppe
#

yes

#

the base url

sonic birch
#

niiice to knwo im a meme

mild bridge
#

hmmmmm

kind steppe
#

no

#

the base url is a meme

sonic birch
#

wait

#

what

#

if i have 8 other variables

#

myarray wouldnt work

#

bc

kind steppe
#

lol what

#

you put the values

#

into myarray

sonic birch
#

for it to work, id' have to redefine a new one for each variable?

#

im not fully understanding

brave mantle
kind steppe
#

oh right

#

yes you would

#

for each one you'd have to run

sonic birch
#

fml

kind steppe
#
var BLAH = ARRAYNAME[Math.floor(Math.random() * ARRAYNAME.length)];
sonic birch
#

true

#

im a BLAH

kind steppe
#

what no

#

the variable is a BLAH

sonic birch
#

i know

#

but

#

im a bleh today

kind steppe
#

yes but the variable is a BLAH?

#

@mild bridge I'm getting flashbacks of bamboozle with aperture

mild bridge
#

yEET

kind steppe
#

yet what

sonic birch
#

lmao

#

@kind steppe that code solution fixed it but broke it as well

#

it does get a random element but it sticks with it all the time now

#

;ole

#

like

#

no matter how many times i reload it

#

its always the same

kind steppe
#

show the code

sonic birch
#

```const gay1 = [gay1, gay2];
var gay = gay1[Math.floor(Math.random() * gay1.length)];

const leb1 = [lesbian1, lesbian2];
var lesbians = leb1[Math.floor(Math.random() * leb1.length)];

const boobs1 = [boob1,boob2];
var boobs = boobs1[Math.floor(Math.random() * boobs1.length)];

const ass1 = [ass1,ass2];
var ass = ass1[Math.floor(Math.random() * ass1.length)];

const pussy1 = [pussy1,pussy2];
var pussy = pussy1[Math.floor(Math.random() * pussy1.length)];

const dick1 = [dick1,dick2];
var dick = dick1[Math.floor(Math.random() * dick1.length)]

const women1 = [women1,women2];
var women = women1[Math.floor(Math.random() * women1.length)]

const men1 = [men1, men2];
var men = men1[Math.floor(Math.random() * men1.length)]

const random1 = [gay, lesbians, boobs, ass, pussy, dick, women, men];
var random = random1[Math.floor(Math.random() * random1.length)];```

#
"gay": "http://isabaseurl.com/gay/gay2.png",
"lesbians": "http://isabaseurl.com/lesbians/lesbian1.png",
"boobs": "http://isabaseurl.com/boobs/boob2.png",
"ass": "http://isabaseurl.com/ass/ass2.png",
"pussy": "http://isabaseurl.com/pussy/pussy1.png",
"dick": "http://isabaseurl.com/dick/dick2.png",
"men": "http://isabaseurl.com/men/men1.png",
"random": "http://isabaseurl.com/random/women2.png"
}```
this never changes
#

maybe its just grabbing like a value higher than 2

kind steppe
#

well

#

what is the response.json

sonic birch
#

still the same

#

hasnt changed

kind steppe
#

well that is why

#

you've made the variables

#

but you've not actually sent them back

#

my dude I seriously recommend a Node.js tutorial

mild bridge
tame viper
#

what even is node.js?

kind steppe
#

javascript but when it escaped the browser

#

sad, I know

tame viper
#

oh okay

sonic birch
#

Oohh I get it

#

@kind steppe It does update with random values; but I have to keep restarting the node.js script for it to take effect

#

so now i have to work out how to make it update with every request

kind steppe
#

make it generate every request

sonic birch
#

yeah i was thinking of doing it that way

#

but im not sure lmao

kind steppe
#

yeah you have to

sonic birch
#

since i wouldnt really know how to really do it properly

#

tutorials here i come

verbal flame
tired lynx
#

Hello, I've installed Django onto my PC

#

I created an app

#

All of this is really complicated-sih

#

*ish

#

Is Flask easier than this?

native tide
#

no

#

it's not really easier, installing everything and making the webserver work is kinda complicated :/

#

especially for development

neat nest
#

hmm... deployment you have a point on, but in terms of the bare minimum requirements for having a functional application, most people would tend to lean towards Flask for simplicity

#

in lemon's words, Flask is "less opinionated" about how you do things

#

if you want to build it into a robust application in the manner of django you can do so, if you want to serve a barebones API for an existing project you're also free to do that

#

so... I'm hesitant to say it's "easier", it depends on the sense, but it's not going to demand as much from you to get going. whether that's good or bad depends on your needs and convictions

meager anchor
#

I think flask is a lot easier to learn, but very often when I'm looking for something in Django - for example, "create a view to edit this objects", "create a view to list all objects" - it's already there. Django comes with this batteries-included approach, and that's really nice

grand badge
#

flask is easier to start with

indigo holly
#

I really enjoy flask. Django gave me nightmares

#

Also,
Can anyone help me troubleshoot this View function did not return a response error?

Everything I've found suggests its an error when the return function isn't used or present. But I can't see what I'm doing wrong with this code:

@app.route('/data', methods=['GET', 'POST'])
def data():
    if request.method == 'POST':
        if request.method == 'POST':
            admin = request.form.getlist('admin')
            if admin == 'root':
                return admin()
    else:
        return render_template('AdminPass.html')

relevant HTML

<form method="POST" action="/data">
      <input type="text" name="admin" placeholder="admin">
meager anchor
#

What's admin()?

indigo holly
#

It's another function, directly below my data() function

meager anchor
#

But a line above, you check if it equals a string

indigo holly
#

So it looks like

@app.route('/data', methods=['GET', 'POST'])
def data():
....
return admin()

def admin()
meager anchor
#

hm

#

I don't know that much about Flask, but I don't think that this is some special thing that you can call after comparing it to a string

indigo holly
#

Hmm. I actually do this in the other function and it works though, lets me show you

neat nest
#

you have an admin =

#

you're shadowing its name

indigo holly
#

Can you explain shadowing in laymans?

meager anchor
#

Also, ```py
if request.method == 'POST':
if request.method == 'POST':

seems a bit redundant
strange thorn
#

@indigo holly your function will not respond in all cases

#

thats what flask doesnt like

meager anchor
#
def add(a, b):
    return a + b

if __name__ == '__main__':
    add = 5
    add(3, 5)  # huh?
strange thorn
#

it wont respond to a request which is a post but hasnt admin == "root"

meager anchor
#

gives TypeError: 'int' object is not callable

#

because you shadowed the add function from outer scope

strange thorn
#

and you have to respond to that case

#

just always respond tbh

#

if you dont have like a default return value at the bottom

#

every if which returns must have an else that returns

#

otherwise it will crash at some point

indigo holly
#

I see..

#
def data():
    if request.method == 'POST':
            admin = request.form.getlist('admin')
            if admin == 'root':
                return admin()
            else:
                return render_template('AdminPass.html') 
    else:
        return render_template('AdminPass.html')
strange thorn
#

yup

indigo holly
#

Isn't this redundant though ๐Ÿ˜ฆ

strange thorn
#

now everything returns

#

what you could do is

indigo holly
#

I know it's right now. I just don't like it haha ๐Ÿ™„

strange thorn
#
def data():
    if request.method == 'POST':
            admin = request.form.getlist('admin')
            if admin == 'root':
                return admin()
    return render_template("AdminPass.html")
indigo holly
#

Thank you for the help! This worked.

strange thorn
#

no problem

native tide
#

How did that work if it's calling a string?

meager anchor
#

Good question GWfroggyPepoThink

native tide
#

"If x is equal to a string which is obviously not callable, call it"

strange thorn
#

When did I call a string??????

meager anchor
#
            admin = request.form.getlist('admin')
            if admin == 'root':
                return admin()
strange thorn
#

That's not me

#

That's just me copying stuff

native tide
#
            admin = request.form.getlist('admin')
            if admin == 'root':
                return 'root'()```
brittle copper
#

You maybe thinking that it is working because it actually never runs and admin never equals to 'root'

#
def data():
    if request.method == 'POST':
        if request.form.getlist('admin') == 'root':
            return admin()
    return render_template("AdminPass.html")```
#

This simply eliminates the shadowing admin variable so should work

#

I'd've maybe guessed that you had an Admin object named admin that you wrote the __eq__ and __call__ but it is not the case apparently

#

Soo

brittle copper
#
def context_manager(template, context = None):
    def actual_decorator(f):
        def wrapper(request, *args, **kwargs):
            _context = f(request, *args, **kwargs).get_context_magically()
            if context is not None:
                _context.update(context)
            _template = loader.get_template(template)
            return HttpResponse(_template.render(_context, request))
        return wrapper
    return actual_decorator
#

@deep cave

#

I'm trying to update the context with a decorator

#

Because in the website almost every function I write has at least 10 common item in the context

deep cave
#

: /

brittle copper
deep cave
#

I'm not sure this is a problem that should be occurring. perhaps it evidences poor site design.

#

but tbh you're in too deep for me to help

brittle copper
#

:3

deep cave
#

I have no idea how you'd do that. if I found myself wanting to do that I'd probably go seek out #django on freenode and have them tell me where I went wrong.

#

seems like an antipattern to me

#

that's a great channel btw for really hairy django stuff

#

most of the maintainers are there

brave mantle
#

I wonder if aera/andrewgodwin is there

deep cave
#

and a ton of exceptionally talented django devs.

brittle copper
#

Hmm, thanks

brave mantle
#

He's a django maintainer, and the origin of my old MC network

brittle copper
#

And this is for uhm, the context as in the user name, the index list etc.

#

They are mostly same in all the pages

deep cave
#

isn't there some sort of global context in django like in flask?

brittle copper
#

Like the index list exist in every singe sub page

#

Is there? That is what I'm trying to do

#

lol

#

God damn it SO

deep cave
#

in flask this is trivial, cause a global context variable comes with flask itself.

#

custom context processor, huh?

brittle copper
#

Wow, something built-in in Flask and not in Django :D

deep cave
#

hmm

#

A context processor has a very simple interface: Itโ€™s a Python function that takes one argument, an HttpRequest object, and returns a dictionary that gets added to the template context.

#

that seems pretty straight forward, no?

#

All Django cares about is that your custom context processors are pointed to by the 'context_processors' option in your TEMPLATES setting

#

and then it's just handled automatically

brittle copper
#

Hmm

#

So they don't make me extract the context from the returned object but

#

All I need to do is to return a dictionary? ๐Ÿค”

deep cave
brittle copper
#

That was uhm

#

Way easier than what I was trying to do

#

I'll take it :D

#

Thanks :D

deep cave
#

not like I did much ยฏ_(ใƒ„)_/ยฏ

#

but you're most welcome, little sir.

gleaming sable
#

I'd like to create a webapp/flask that has a form users will fill out. Upon submisison they will be routed to a printable page of their data. I'd like them to be able to save a version to edit or re-upload and populate the form. What type of file would you suggest?

#

I don't want to store the data for the user. I was thinking of maybe giving them the option to save a JSON file or something similiar.

brittle copper
#

This is something can be done with js

brave mantle
#

Technically speaking, you don't need to store the data, but it depends what you're doing

#

yeah, client-side JS is one option

gleaming sable
#

Just looking for ideas, i'm new to python.

#

The goal being to replace a hand filled out form that they are currently using. I figured a webapp would be the way to go since future upgrades would be easier to distribute. There are many features that would be nice to implement including electronic submission way down the line.

brittle copper
#

I mean you really wouldn't want to use your server machine for simple stuff like that

#

You can use flask for backend

#

And make a js that handles the form thing

gleaming sable
#

@brittle copper ?

brittle copper
#

A question mark isn't a question

gleaming sable
#

@brittle copper What do you mean you wouldn't use a server for simple stuff like that?

brittle copper
#

If what user is doing doesn't concern you, if you don't log it, if you don't add new information to it

#

You wouldn't do it on the back end

#

Rather you'd use js

#

And do it in client side

gleaming sable
#

Is there a way to interact with a FlaskForm object from flask_wtf in the REPL?

#

disregard found the working with the shell flask page

cyan pilot
#

@quartz maple Are you familiar with Beautiful Soup and Requests?

quartz maple
#

I know of them

cyan pilot
#

I recommend using BS4 for getting info from websites that don't have an API

polar vessel
#

Could a django expert check my models.py and verify if my ForeignKey logic is in order?

#
    first_name = models.CharField(max_length = 50)
    last_name = models.CharField(max_length = 50)

    def __str__(self):
        return "{} {}".format(self.first_name, self.last_name)


class ClassNumber(models.Model):
    classNum = models.IntegerField()

    def __str__(self):
        return self.classNum

class SchoolDay(models.Model):

    DAY_CHOICES = (('Monday', 'Mon'), 
                   ('Tuesday', 'Tue'), 
                   ('Wednesday', 'Wed'),
                   ('Thursday', 'Thu'),
                   ('Friday', 'Fri'),)

    schoolDay = models.CharField(max_length=3, choices=DAY_CHOICES)
    classNumber = models.ForeignKey('ClassNumber', on_delete=models.CASCADE)

    def __str__(self):
        return self.schoolDay



class Schedule(models.Model):

    teacher = models.ForeignKey('Teacher', on_delete=models.CASCADE)
    day = models.ForeignKey('SchoolDay', on_delete=models.CASCADE)
    ```
#

I've honestly tried everything i know for my ModelForms to render in html but it won't show what I'd like

meager anchor
#

bot.tags['ask']

lavish prismBOT
#
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.

meager anchor
#

we can't really help you much from that question

dense sapphire
#

does anyone know of any web scanner for NGINX specifically?

#

Or mebe making a scanner focus mainly on nginx vulns

brave mantle
#

Huh, that's kind of an odd request

#

What're you workin' on?

dense sapphire
#

i am configuring an nginx server with a web app on top. I am simply practicing. I want to see if there any specific scanner for nginx servers. My server was detected by other scanners as vulnerable (it is), just want to make sure that there are no specific nginx ones

brave mantle
#

There aren't

#

Your best bet is metasploit

#

..if they'll let you use it

dense sapphire
#

why not, the server is mine ๐Ÿ˜œ

brave mantle
#

They have an approval process

#

:P

dense sapphire
#

Hahaha

#

I'll make sure to email them

#

Should I include any special requests other than breaking the web server?

brave mantle
#

Read the site

#

It'll tell you what you need

dense sapphire
#

wait .. um, you lost me over there

brave mantle
#

the site

dense sapphire
#

Did i miss a joke or something pepe

brave mantle
#

for metasploit?

dense sapphire
#

oh haha, the site is local bb. Everything is mine

#

I told you I am practicing

brave mantle
#

...

#

no

dense sapphire
#

goddem

brave mantle
#

the METASPLOIT SITE

#

lol

dense sapphire
#

omg are you telling me what i need to work on metasploit? yoj

#

imma kms for not understanding you

#

i hope i did this time

deep cave
#

oh dear

dense sapphire
#

hahaha i know of it. I didn't grasp if gdude was messing with me or nut (in the end i did)

#

I am not a newbie in security, therefore I thought he was messing with me somewhere in there

deep cave
#

there was no ambiguity

keen crest
#

I can't figure out where the resources page on the discordpython site gets its icons from json "Automate the Boring Stuff with Python": { "description": "One of the best books out there for Python beginners. You can buy a copy, but there's also a free online version.", "urls": [ { "title": "Website", "url": "https://automatetheboringstuff.com/", "icon": "regular/link" }, { "title": "Amazon", "url": "http://www.amazon.com/gp/product/1593275994/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1593275994&linkCode=as2&tag=playwithpyth-20&linkId=HDM7V3T6RHC5VVN4", "icon": "branding/amazon" } ], "payment": "optional", "payment_description": "A free version is available online, with the option to buy a physical copy" },

#

see "icon": "branding/amazon"

#

it's not in the CSS and I can't find it in a fulltext search of the whole site repo

strange thorn
#

It's in the branding repository

keen crest
#

argh

#

I've never heard of this before

#

I'm browsing the branding repository and I have two questions... one, how does this get included into the site and CSS, I can't find any references to it in the site project. Two, there aren't any youtube or amazon icons in here but they are in the resources JSON and they work, where are they coming from?

keen crest
#

@mild bridge

mild bridge
#

The icons are fontawesome icons

#

they're not in the branding repo

#
ICON_STYLES = {
    "branding": "fab",
    "regular": "far",
    "solid": "fas",
    "light": "fal"
}
#
            for name, resource in items["resources"].items():
                for url_obj in resource["urls"]:
                    icon = url_obj["icon"].lower()

                    if "/" not in icon:
                        to_remove.append(name)
                        logger.error(
                            f"Resource {name} in category {category} has an invalid icon. Icons should be of the"
                            f"form `style/name`."
                        )
                        continue

                    style, icon_name = icon.split("/")

                    if style not in ICON_STYLES:
                        to_remove.append(name)
                        logger.error(
                            f"Resource {name} in category {category} has an invalid icon style. Icon style must "
                            f"be one of {', '.join(ICON_STYLES.keys())}."
                        )
                        continue

url_obj["classes"] = f"{ICON_STYLES[style]} fa-{icon_name}"
keen crest
#

thank!

mild bridge
#

๐Ÿ‘

deep cave
#

roons, your bot is hooked up to a database, right?

midnight spoke
#

hey guys im wanting to have my bot configurable through a web interface, whats the best way of starting that?

#

database and yaml as settings

deep cave
#

ah, you're using yaml currently

#

okay

#

but

#

the bot, will it be on the same server as the web interface?

midnight spoke
#

yupyup it will be

#

makes it a lot easier right?

deep cave
#

and do you want to keep the yaml as well?

#

or just replace it

midnight spoke
#

urmmm not too sure really dude

deep cave
#

either way;

#

you want those configurables in your database.

midnight spoke
#

okies, mysql is fine right?

deep cave
#

then have the bot pull them in from the db when it boots up

midnight spoke
#

sqllite sorry

deep cave
#

any database is fine

#

and then

#

your web interface

#

just goes to the same table, same database

#

fetches all those settings

#

and lets you fuck with them, and saves them again.

#

if you want things to change live, you'd need to somehow tell the bot to reload those settings.

midnight spoke
#

oh yeah...

#

that actually had slipped my mind

#

is there any reading material you recommend to starting something like this?

#

i basically know NOTHING about webdev

deep cave
#

hm. well, flask would be good for this.

midnight spoke
#

okays ๐Ÿ˜ƒ

deep cave
#

and it has plenty of useful reading material easily available.

midnight spoke
#

ive heard of flask

#

and django

deep cave
#

we use it for our website

#

flask could do this and still basically be a single file.

#

django could do this too, of course. but it would be a big project with many many files.

#

for that reason alone I'd recommend flask for this.

midnight spoke
#

gotcha

deep cave
#

perhaps you should start by just doing a flask hello world

#

their official quick start guide isn't bad

#

and feel free to lean on us. we got lots of flaskers in here

meager anchor
#

wouldnโ€˜t using flask as a web interface for a bot be blocking though?

#

or would you run them separately?

deep cave
#

yeah of course, seperately.

meager anchor
#

ah

deep cave
#

@midnight spoke

but the basic idea is - you'll make a jinja template file (kind of like a normal html page but with certain special tags that allow you to write some python-esque code on the page). in this file you'll loop through some a dictionary with all the config settings and display a field for each configurable, pre-filled with its current value. At the bottom there'll be a submit button.

Then you'll have the flask file itself, which when you load the page in your browser, will contact the database, get all the configurables, and then pack them into a dictionary which it will spit out together with that template.

lastly the flask file will also respond when you do a POST request (so when you hit the submit button on that page), and then it will take all the changed configs and spit them back into the database.

#

it's as simple as that

#

then once you have that working, you can figure out how to have it restart the bot automatically and fancy stuff like that

#

it'll probably involve websockets.

#

but don't worry about that yet.

brittle copper
#

Does the bot need restarting tho

deep cave
#

probably not, you could just update the relevant variables on the fly instead if the configurables are hot-seatable.

brittle copper
#

Yeah that sounds better tbh

deep cave
#

depends on whether he's configuring stuff like, uh, the bot token

#

but yeah for most config you probably wouldn't need a restart.

midnight spoke
#

okies thanks guys, its something i'll have a look into โค

deep cave
#

knowing you, you'll have it figured out in a week

midnight spoke
#

lol probably not, but i'll give it a good go!

#

us beginnners are not that fast ๐Ÿ˜‰

deep cave
#

this guide looks relatively inoffensive

#

but please put style in a .css file, not in <style> tags

#

or I will hunt you down

midnight spoke
#

๐Ÿ˜„ yessir!!

brittle copper
#

I mean for something simple like this I'd use a prewritten template :3

#

Of course you would. -Lemon

deep cave
#

:D

#

I was gonna say that

brittle copper
#

lol :D

deep cave
midnight spoke
#

i like to learn though

deep cave
#

writing a template and styling it is a great opportunity to learn some jinja and css

brittle copper
#

Learn html and css?

midnight spoke
#

and web pages confuse me ๐Ÿ˜ƒ

deep cave
#

and those are wonderful tools

#

css is one of my favorite things, and I'll be only too glad to help you with it if you get stuck.

midnight spoke
#

thanks buddy

#

i need to make the bot write everything to sql instead of yaml and write some nice wrapper functions

deep cave
#

yep

#

why sqllite though

#

I was sure you had a database

midnight spoke
#

i think courier is on about 13 servers now

deep cave
#

cool!

midnight spoke
#

i do have a database i store quotes and league and battlenet data in there

deep cave
#

yes. what kind is that again?

midnight spoke
#

sqllite

deep cave
#

oh

#

you know

#

when I said "I thought you had a database"

#

I meant that I thought you had a real database

midnight spoke
#

mutters

#

i have to be careful, i only have the smallest droplet

deep cave
#

mkay

#

yeah well for something like this sqllite is fine

#

even the yaml file would have been okay, tbh

#

I mean - you could just load that into your flask as well

midnight spoke
#

true dat

deep cave
#

I assume you already have pyyaml so that might be the easiest solution - and then you maintain the local configurability

midnight spoke
#

i do have pyyaml yup

deep cave
#

no extra dependencies either then if they're in the same environment

#

fuck sqllite then, just keep it in yaml and rewrite the yaml file

midnight spoke
#

to be fair the yaml isnt big at all

#

105 lines

deep cave
#

that's not nothing

#

but yeah I would just do that then

#

and then

#

this is the cool bit

#

you could just update the yaml if you need a new setting

#

and the website would just dynamically change

midnight spoke
#

Sexah

deep cave
#

do you run your bot with a supervisor?

midnight spoke
#

i sure do my friend

deep cave
#

then a super easy solution would be

#

have the website restart the service

#

you don't even need to communicate between the two

midnight spoke
#

cmonnnn man...

#

i can do better than that

deep cave
#

the flask script can just do supervisorctl restart bot

#

yeah you can probably do better

#

it just might be a lot more code for no real benefit

midnight spoke
#

the real benefit is, no bot restart, and no downtime

deep cave
#

I guess ยฏ_(ใƒ„)_/ยฏ

midnight spoke
#

and the bot is in charge of a discord server which it assigns roles

#

which they have to agree to welcome text

#

it has about 800 members so far?

deep cave
#

well then you might do something like making the bot watch the yaml for changes and reload its config when the file updates. or you might send the bot a message via something like rabbitmq to let it know what to update.

midnight spoke
#

and besides, reloading the config is sexier!

mental chasm
#

How is SQLite not a real database

grand badge
#

wat

deep cave
#

can we not

grand badge
#

it is a real database

mental chasm
#

Read up ImportError

#

@deep cave I'm happy to ask you in #databases if you wish

deep cave
#

I'd be happier if you just didn't ask me. fine it's a real database, debate over.

mental chasm
#

Lol

midnight spoke
#

lemon was just having a bit of fun with me, we do that a lot

mental chasm
#

Don't say questionable things, and questions won't get asked :)

grand badge
#

sqlite is very gud

deep cave
#

you're disregarding the context to make a thing out of something that wasn't a thing

mental chasm
#

He could have explained that, context is a wonderful thing

midnight spoke
#

we had a conversation

#

steps away

deep cave
#

sqllite is fine. I'm a fan of sqllite

mental chasm
#

One L

midnight spoke
#

someone fell outta the grouchy tree today

deep cave
#

I just thought runewolf had a fully fledged database. I thought he had cairosdb or rethinkdb or something already and was wondering why he wouldn't be using that. I guess my memory failed me.

mental chasm
#

It's one of those really pedantic points I know, but it's kinda one of those things that really annoy you when they shouldn't lol

midnight spoke
#

yeah ive had 3 databases so far, as well as yaml and json

#

all in 1 bot

deep cave
#

basically I wasn't saying "not a real database" as in "sqlite sucks", I was saying it as in "as opposed to something huge like postgre"

midnight spoke
#

its no wonder you cant keep up with what ive h ad in there

mental chasm
#

I still think not a real database is wrong choice of words

deep cave
#

probably

mental chasm
#

And leaves you open to this exact debate

grand badge
#

yes, sqlite is shit compared to postgres

deep cave
#

it's not shit

mental chasm
#

Why would you compare them anyways

grand badge
#

compared to postgres

deep cave
#

it's just a different tool for a different problem

grand badge
#

^

mental chasm
#

??????????

grand badge
#

?

mental chasm
#

You just said it's shit, and then agreed with lemon who was arguing against your point ๐Ÿค”

grand badge
#

wat

#

I said its shit compared to postgres

mental chasm
#

But the point is, you don't compare them

grand badge
#

but it has its uses, for small projects

deep cave
#

are you guys a comedy duo

mental chasm
#

They have different purposes

deep cave
midnight spoke
deep cave
grand badge
midnight spoke
grand badge
#

Wtf

midnight spoke
#

sorry mum

brittle copper
#

Jason_000 - Today at 5:57 PM
How is SQLite not a real database```
#

Who said it isn't?

#

I demand an answer, who said it isn't a real database

deep cave
#

SCROLL.

strange thorn
#

22 chills pills a day...

grand badge
#

40***

midnight spoke
#

so i have an EXTREMELY basic flask app running, however the stylesheet doesnt seem to be working?

#

so this is test.html

{% extends "layout.html" %}
{% block body %}
 
<div class="block1">
<h1>Hello {{name}}!</h1>
  <h2>Here is an interesting quote for you: </h2>
  <p>
{{quote}}
  </p>
<img src="http://www.naturalprogramming.com/images/smilingpython.gif">
</div>
{% endblock %}
#

This is layout.html

#
<html>
<head>
    <title>Website</title>
    <link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
 {% block body %}{% endblock %}

</body>
</html>
#

and this is the stylesheet

#
@import url(http://fonts.googleapis.com/css?family=Amatic+SC:700);
body{
    text-align: center;
}
h1{
    font-family: 'Amatic SC', cursive;
    font-weight: normal;
    color: #8ac640;
    font-size: 2.5em;
}
deep cave
#

flask wants you to import static files with some special url_for jinja syntax.

#

including the stylesheet

#

so put the stylesheet in a folder called static

#

and see how they import it here

midnight spoke
#

okies ๐Ÿ˜ƒ

#

\o/

#

Okies, thats great!

#

thankyou lemon!

#

and now.....

#

time for bed!!

grand badge
#

if fixed it

#

finally found something useful about css positioning

elfin pasture
#

hey guys, nice to meet you all! I'm in the process of learning django to build a recipe website for fun

#

I wanted to double check whether my current thought process towards the website was correct:

  1. Since my edit recipe page requires some jquery/ajax my logic was that I would build a rest api for the jquery

  2. At that point I figured it may be good practice to decouple the front end as well.

  3. Since i'd be using that instead of MVC, I wouldn't be using ModelForms and instead would just be using HTML forms

meager anchor
#

if you don't use the built-in forms, you'll need to handle validation yourself

deep cave
#

that looks a bit funky and also a bit fresh.

#

@grand badge I hope you fixed it with flexbox.

midnight spoke
#

So ive had a thought, if i people to change the settings on the bot, then they have to log into the website with discord so they only change their details. How would i even go about doing that?

grand badge
#

uhm, wats flexbox @deep cave ?

deep cave
#

it's the solution to that problem in 2018

#

but I'm guessing you used floats instead

#

@midnight spoke we support discord OAuth on our site

#

and a few other ones

#

you can see this PR

#

that's our OAuth PR

#

there's 12 files changed in total, so look through the changes and you should get a rough idea.

midnight spoke
#

sweet baby jesus its not easy

#

thanks lemon

deep cave
#

it's not super easy. we've done it in a way so that we can restrict certain views and there's mixins and there's backend / frontend seperation and lots of extra stuff here

#

you could write a far leaner implementation