#web-development

2 messages ยท Page 19 of 1

tepid saffron
#

you can make your own custom jinja functions

steel tiger
#

ooh

#

that sounds.. weird?

tepid saffron
#

nah?

#

atleast

#

if you use flask for example

#

you can add python functions to jinja

#

and execute them within your template

steel tiger
#

yep its everything

#

no other tags

#

just that specific one

#

also do you be ok with me using sqlite in development with a small website ๐Ÿ˜‰

tepid saffron
#

yeah why not ?

steel tiger
#

some other people get angwy

tepid saffron
#

idc what you use ๐Ÿ˜›

steel tiger
#

mm

tepid saffron
#

I mean, i use sqlite3 + sqlalchemy

steel tiger
#

im just going to use sqlite for small projects

tepid saffron
#

so i can make relations

steel tiger
#

yeah me aswell

#

(learning it atm, bit stuck on relationships with it but trying again tomorrow)

tepid saffron
#

they have it really nice documented

steel tiger
#

im liking flask more than django even if the django orm is better

#

yeah

tepid saffron
#

i do not agree

#

but everyone his thing

steel tiger
#

i like the simplicity of it but i know that sqlalchemy is better at more complicated things

tepid saffron
#

~~on the django part ~~

steel tiger
#

flask is best for short and long term

#

django is best for mid term

tepid saffron
#

I would choose flask over django just because you really install what you need and nothing else

steel tiger
#

yeah

#

can be tricky getting rolling kinda thing but once you have built a nice infastructure for everything, its nice to use

tepid saffron
#

it really is

steel tiger
#

also my pc has 64gb disk space (cheap netbook that i hacked linux onto) so i dont really have space for django with small projects

tepid saffron
#

maybe a idea to look into a docker container running a alpine postgress container if you are short on space

#

good replacement for sqlite3

steel tiger
#

i am making a cloud server

#

got the hard drive

#

got the server

#

only problem is locally-hosted cloud servers are way slower than something like dropbox for whatever reason

#

its weird

tepid saffron
#

maybe configuration settings

steel tiger
#

whats the point of backref in sqlalchemy when dealing with relationships?

#

i understand all of the basics but just not what the backref is used for

#
class Puppy(db.Model):
    __tablename__ = 'puppies'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Text)
    # one to many relationship. ([STRING: What your connecting], backref=[STRING: Name so the connected model can use???], lazy=[STRING: leave dynamic most of the time])
    # Puppy --> Many Toys
    toys = db.relationship('Toy', backref='puppy', lazy='dynamic')
    # one to one
    # Puppy --> One Owner
    owner = db.relationship('Owner', backref='puppy', uselist=False) # leave lazy to default, dont use list but just 1 item

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        if self.owner: # if puppy has owner
            return f'<name: {self.name}, owner: {self.owner.name}>'
        else:
            return f'<name: {self.name}, no owner>'
    
    def report_toys(self):
        print('Here are my toys:')

        for toy in self.toys:
            print(toy.item_name)


class Toy(db.Model):
    __tablename__ = 'toys'

    id = db.Column(db.Integer, primary_key=True)
    item_name = db.Column(db.Text)
    # connect toys to puppies. puppies is Puppy's __tablename__ and we are getting the id of it
    puppy_id = db.Column(db.Integer, db.ForeignKey('puppies.id')) 

    def __init__(self, item_name, puppy_id): # when you make this, it always has to have a name and puppy that owns it
        self.item_name = item_name
        self.puppy_id = puppy_id


class Owner(db.Model):
    __tablename__ = 'owners'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Text)
    puppy_id = db.Column(db.Integer, db.ForeignKey('puppies.id')) # owner connected to puppy, as said above

    def  __init__(self, name, puppy_id):
        self.name = name
        self.puppy_id = puppy_id
#

nowhere is puppy used

pine plover
#
@app.route('/login')
async def login():
    DISCORD_OAUTH_URL = "https://discordapp.com/api/oauth2/authorize?client_id=538438973052289084&redirect_uri=http%3A%2F%2F127.0.0.1%3A5000%2Flogin&response_type=code&scope=email%20identify%20guilds%20guilds.join"
    CODE = request.args.get("code")

    if not CODE:
        return quart.redirect(DISCORD_OAUTH_URL)
    else:

        payload = {
            "client_secret": "censored",
            "client_id": bot.user.id,
            "grant_type": "authorization_code",
            "code": CODE,
            "redirect_uri": "http://127.0.0.1:5000/login",
            "scope": "guilds%20guilds.join%20identify%20email"
        }
        headers = {
            "Content-Type": "application/x-www-form-urlencoded"
        }

        async with bot.session.post(f"{API_ENDPOINT}/oauth2/token", headers=headers, json=payload) as resp:
            resp = await resp.json()
#

This is the code

#

and this is the error: RuntimeError: Timeout context manager should be used inside a task

#

@brave mantle

brave mantle
#

That's not enough of a traceback

pine plover
#
Traceback (most recent call last):
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\quart\app.py", line 1462, in handle_request
    return await self.full_dispatch_request(request_context)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\quart\app.py", line 1484, in full_dispatch_request
    result = await self.handle_user_exception(error)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\quart\app.py", line 911, in handle_user_exception
    raise error
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\quart\app.py", line 1482, in full_dispatch_request
    result = await self.dispatch_request(request_context)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\quart\app.py", line 1530, in dispatch_request
    return await handler(**request_.view_args)
  File "C:/Users/HP/PycharmProjects/quarttest/test.py", line 63, in login
    async with bot.session.post(f"{API_ENDPOINT}/oauth2/token", headers=headers, json=payload) as resp:
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\aiohttp\client.py", line 855, in __aenter__
    self._resp = await self._coro
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\aiohttp\client.py", line 321, in _request
    with timer:
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\aiohttp\helpers.py", line 658, in __enter__
    raise RuntimeError('Timeout context manager should be used '
RuntimeError: Timeout context manager should be used inside a task
#

Full traceback

#

@brave mantle

brave mantle
#

Where did you create your aiohttp session?

pine plover
#

In my bots subclass

brave mantle
#

OK, where?

pine plover
#
class Bot(commands.Bot):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.dashboard = Dashboard()
        self.session = aiohttp.ClientSession(loop=self.loop)
brave mantle
#

that'll be it

#

They're supposed to be created within a coroutine

#

you could use the on_ready event

pine plover
#

Alright

#

Thanks

pine plover
#
if quart.request.method == "POST":
    nick = (await quart.request.form)["nick"]
    guild = bot.get_guild(id)
    __bot_user = guild.get_member(bot.user.id)
    await __bot_user.edit(nick=nick)
    return "Changed nick!"
#

Error:

Traceback (most recent call last):
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\quart\app.py", line 1462, in handle_request
    return await self.full_dispatch_request(request_context)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\quart\app.py", line 1484, in full_dispatch_request
    result = await self.handle_user_exception(error)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\quart\app.py", line 911, in handle_user_exception
    raise error
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\quart\app.py", line 1482, in full_dispatch_request
    result = await self.dispatch_request(request_context)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\quart\app.py", line 1530, in dispatch_request
    return await handler(**request_.view_args)
  File "C:/Users/HP/PycharmProjects/quarttest/test.py", line 121, in dashboard
    await __bot_user.edit(nick=nick)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\discord\member.py", line 479, in edit
    await http.change_my_nickname(guild_id, nick, reason=reason)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\discord\http.py", line 154, in request
    async with self._session.request(method, url, **kwargs) as r:
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\aiohttp\client.py", line 855, in __aenter__
    self._resp = await self._coro
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\aiohttp\client.py", line 321, in _request
    with timer:
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\aiohttp\helpers.py", line 658, in __enter__
    raise RuntimeError('Timeout context manager should be used '
RuntimeError: Timeout context manager should be used inside a task
#

@brave mantle

brave mantle
#

No idea at this point

#

It's kind of a weird error

pine plover
#

I think it's because of await __bot_user.edit(nick=nick)

steel tiger
#

is there any normal first "public" website that people make?

#

im going to make a server list, similar to a blog but edited for servers (as in users post game servers and people can like them, like you can do with blogs)

native tide
#

(Django ) I'm trying to get my form to display a quiz with its questions - and it does with a GET request. But creating a form instance with POST request doesn't work - request.POST contains dict with strings (answers to questions) while my form's init expects a questions argument.

#
class QuizPageForm(forms.Form):
    def __init__(self, questions, *args, **kwargs):
        super(QuizPageForm, self).__init__(*args, **kwargs)
        for counter, question in enumerate(questions):
                choice_list = []
                for choice in (question.get_choices()):
                    choice_list.append((choice.pk, choice.choice_text))
                self.fields["question{}".format(counter)] = forms.ChoiceField(label=question.get_question_text(),
                                                                              choices=choice_list,
                                                                              widget=forms.RadioSelect)
rancid rose
#

Can anyone help me find material static UI templates for a web app related to Disaster Response. The web app will be using Google Maps API.

gritty locust
#

Hello Guys, How can I serve CSS and JS files on an Aiohttp web app?

spring mist
#

can any one help me in the project structure of flask api

patent cobalt
primal sinew
#

@coral ridge and @native tide - Having some problems with this now. Any thoughts?

#
function copyMessage() {
    var copyText = document.getElementById("encryptedMessage");
    var copyBttn = document.getElementById("copyText");  

    if (copyBttn.click()) {
        copyText.select();
        document.execCommand("copy");
        alert("Copied your encrypted message to the clipboard!");
    }
}
#
{% extends 'layout.html' %}
{% from 'bootstrap/form.html' import render_field %}

{% block body %}

    <br />

    <div class="alert alert-success" role="alert">
        <h2 style="text-transform: uppercase; font-weight: bold; text-align: center;">Your Original Message:</h2>
        <p style="text-align: center;">{{ user_message }}</p>
    </div>
    
    <br />

    <div class="alert alert-secondary" role="alert">
        <h2 style="text-transform: uppercase; font-weight: bold; text-align: center;">Your Encrypted Message:</h2>
        <p id="encryptedMessage" style="text-align: center;">{{ output }}</p>
    </div>

    <br />

    <div class="alert alert-danger" role="alert">
        <h2 style="text-transform: uppercase; font-weight: bold; text-align: center;">Your Secret Key:</h2>
        <p style="text-align: center;">{{ secret_key }}</p>
    </div>

    <br />

    <button type="button" onclick="copyMessage()" id="copyText" class="btn btn-primary btn-lg btn-block">Copy message to clipboard</button>

    <br />

    {% with messages = get_flashed_messages() %}
        {% if messages %}
            <div class="alert alert-success" role="alert">
                {{ messages }}
            </div>
        {% endif %}
    {% endwith %}

{% endblock %}
#

Or if anyone else has any thoughts would be greatly appreciated. Thanks in advance.

hallow raft
#

I think you forgot the for loop

#

in the flashed messages

primal sinew
#

Pardon?

#

@hallow raft

hallow raft
#

the flashed messages is not displaying correctly right?

primal sinew
#

No sorry it's not running the JS correctly as in it's not copying the test and displaying the confirmation alert.

hallow raft
#

I think it's because you called .click() as a method and it returns undefined

primal sinew
#

So I would need to attach a function to it? For example...

hallow raft
#

you want the code to invoke on click right?

primal sinew
#

Yes please.

hallow raft
#

you have to hook to the click event with copyBttn.addEventListener

primal sinew
#
copyBttn.addEventListener('click');

    if (copyBttn.click()) {
        copyText.select();
        document.execCommand("copy");
        alert("Copied your encrypted message to the clipboard!");
    }
hallow raft
#

put the 2nd argument of .addEventListener as the function to invoke when it's clicked

primal sinew
#
if (copyBttn.click(), copyBttn.addEventListener) {
        copyText.select();
        document.execCommand("copy");
        alert("Copied your encrypted message to the clipboard!");
}
#

Sorry.

#
if (copyBttn.click(copyBttn.addEventListener) {
        copyText.select();
        document.execCommand("copy");
        alert("Copied your encrypted message to the clipboard!");
}
hallow raft
#

like

copyBttn.addEventListener("click", function(event) {
    // the rest here
})
primal sinew
#
if (copyBttn.addEventListener("click", copyMessage())) {
        copyText.select();
        document.execCommand("copy");
        alert("Copied your encrypted message to the clipboard!");
}
hallow raft
#
copyBttn.addEventListener("click", function(event) {
    copyText.select();
    document.execCommand("copy");
    alert("Copied your encrypted message to the clipboard!");
})```
primal sinew
#

Yeah sorry I was just reading up on it and noticed that is the correct way of doing it. Apologies. I will try this.

#

It's not accepting the request so I think it may be a problem with linking the static file.

#

No it's still not working.

coral ridge
#

@primal sinew What is not working?

primal sinew
#

It would appear the whole entire script at this point. Here is the JS code.

#
function copyMessage() {
    var copyText = document.getElementById("encryptedMessage").innerHTML;  
    copyText.select();
    document.execCommand("copy");
    alert("Copied your encrypted message to the clipboard!");
}

document.getElementById("copyText").addEventListener("click", copyMessage);  
#

Here is my template...

#
{% extends 'layout.html' %}
{% from 'bootstrap/form.html' import render_field %}

{% block body %}

    <br />

    <div class="alert alert-success" role="alert">
        <h2 style="text-transform: uppercase; font-weight: bold; text-align: center;">Your Original Message:</h2>
        <p style="text-align: center;">{{ user_message }}</p>
    </div>
    
    <br />

    <div class="alert alert-secondary" role="alert">
        <h2 style="text-transform: uppercase; font-weight: bold; text-align: center;">Your Encrypted Message:</h2>
        <p id="encryptedMessage" style="text-align: center;">{{ output }}</p>
    </div>

    <br />

    <div class="alert alert-danger" role="alert">
        <h2 style="text-transform: uppercase; font-weight: bold; text-align: center;">Your Secret Key:</h2>
        <p style="text-align: center;">{{ secret_key }}</p>
    </div>

    <br />

    <button type="button" id="copyText" class="btn btn-primary btn-lg btn-block">Copy message to clipboard!</button>

    <br />

    {% with messages = get_flashed_messages() %}
        {% if messages %}
            <div class="alert alert-success" role="alert">
                {{ messages }}
            </div>
        {% endif %}
    {% endwith %}

{% endblock %}
coral ridge
#

Where are you including the script?

primal sinew
#

I have tried in the main layout template file as well as the one above using url_for()

coral ridge
#

<script type="text/javascript" src="{{ url_for('static', filename='main.js') }}"></script>

primal sinew
#

Yes that is what I have included but still no joy.

coral ridge
#

Even the text/javascript part? Leaving it out will cause the script to not work

primal sinew
#

No even that as well.

#

Is there any faults with the JS code at all that's all I can think of?

coral ridge
#

I'm not a JS expert but you don't need document.getElementById("copyText").addEventListener("click", copyMessage);

#

You can just do

<button type="button" id="copyText" class="btn btn-primary btn-lg btn-block" onclick="copyMessage()">Copy message to clipboard!</button>
#

Also you can try if the function works by opening the dev console and calling the function there

primal sinew
#

OK leave with me and I will have another play. Really appreciate you taking the time to help though.

#

Yeah there are errors with the JS code. Thanks for the suggestion of the dev tools. This will help.

rough jasper
#

how can i make a form and let the user decide the method with a <select>

#

??

coral ridge
#

@primal sinew I think the thing is that it has to be an input field you are copying from

primal sinew
#

Yeah I have just thought of that. I will try this and give it a go. Leave with me.

#

Nope same thing. Still getting error of copyText.select is not a function

#

It looks as if there is an issue with javascript copyText.select();

#

Sorted it @coral ridge and @hallow raft . Was including an additional innerHTML tag that wasn't required. Thanks for your help.

coral ridge
#

Cool! ๐Ÿ‘

gleaming drift
#

Is anyone here able to answer a socket handshake related question?
TCP/IP protocol

polar robin
#

i got {% if g.user %} <p style="display:inline">Welcome back!</p> {% if not g.user.membership %} <a href=" {{ url_for('apply') }}">Apply.</a> {% endif %} <a href=" {{ url_for('profile') }}">Profile.</a> <a href=" {{ url_for('logout') }}">Logout.</a> {% else %} <p style="display:inline">You are not logged in.</p> <a href=" {{ url_for('login') }}">Login.</a> {% endif %} and I'm getting 'NoneType' object has no attribute 'membership' but it should never get to that point if g is NoneType. i assume im wrongly nesting if statements?

rancid rose
#

anybody know how to setup leaflet plugins in django by using django-leaflet or any other way ? I want to add leaflet-sidebar plugins.

inland veldt
#

@polar robin not sure if you solved your issue, but in Jinja you need to use the builtin test none: if g.user is not none

upper trellis
alpine socket
#

hey, im trying to make to backend todo app in django rest framework and i want to know how can you move a json object into another model when there is a get request on a certain url. Please help

#

I have made the api to return a list of all the tasks and to add new tasks. Now i need help with how to move the tasks into another table of "Completed tasks"

alpine socket
#

no one?

brave mantle
#

Nobody's answered you because the correct answer is "that's not what you want"

#

You should have a single table for tasks and have a completed column

#

SQL databases are designed to work across large tables with lots of rows

#

rather than a bunch of smaller tables

#

In order to keep things optimised, you should avoid "moving" rows between tables

#

(realistically, that move is not a move, it's a deletion of the row in the first table and an insertion into the other one)

alpine socket
#

okay thanks...ill work on that! ๐Ÿ˜ธ

alpine socket
#

ITS WORKING!! ๐ŸŽŠ

primal sinew
#

All of a sudden my app is not display bootstrap correctly from it's module when I include html {% from 'bootstrap/form.html' import render_field %} in my template. Any idea what could cause this? I have since worked on my scripts today but as of this morning everything was working correctly.

primal sinew
#

Never mind, sorted it thanks.

primal sinew
#

I am trying to decrypt an existing encrypted message. Basically the user will paste the encrypted message and private key into a form and it would show the decrypted output. Here is the code.

#
@app.route('/decrypted')
def decrypted():
    # Registering forms
    decrypt_form = DecryptMessage(request.form)
    decrypt_form.validate_on_submit()

    # Pulling data from form
    m = decrypt_form.message_field.data
    k = decrypt_form.key_field.data

    # Converting private key to bytes
    k_bytes = k.encode(encoding='UTF-8')

    # Generate new key
    base64_key = base64.b64encode(bytes.decode(k_bytes))
    g = Fernet(base64_key)

    # Decrypt message
    decrypt_message = g.decrypt(m)
    final_output = decrypt_message

    return render_template('decrypted.html', final_output=final_output)
#

I get an error in debug mode stating TypeError: a bytes-like object is required, not 'str'

#

I assume this is something to do with assigning a new key?

#

Any suggestions would be greatly appreciated. Many thanks in advance.

alpine socket
#

which line is the error?

primal sinew
#

I think it maybe the line python base64_key = base64.b64encode(bytes.decode(k_bytes))

alpine socket
#

U dont need to use python bytes.decode(k_bytes)U use it like: python k_bytes.decode()the decode() function takes an argument encoding= but the default is UTF-8 so u dont need to pass that arguement

#

I thinks this should work @primal sinew

primal sinew
#

@alpine socket Amended code ```python
@app.route('/decrypted')
def decrypted():
# Registering forms
decrypt_form = DecryptMessage(request.form)
decrypt_form.validate_on_submit()

# Pulling data from form
m = decrypt_form.message_field.data
k = decrypt_form.key_field.data

# Converting private key to bytes
k_bytes = k.encode()

# Generate new key
base64_key = base64.urlsafe_b64encode(k_bytes.decode())
g = Fernet(base64_key)

# Decrypt message
decrypt_message = g.decrypt(m)
final_output = decrypt_message

return render_template('decrypted.html', final_output=final_output)
alpine socket
#

yes ๐Ÿ‘

primal sinew
#

@alpine socket Sadly not. Still getting the same error. ๐Ÿ˜ฆ

alpine socket
#

the urlsafe_b64encode() takes a bytes like object hence you do not need to decode the variablek_bytes

#

@primal sinew

primal sinew
#

@alpine socket ```python
@app.route('/decrypted')
def decrypted():
# Registering forms
decrypt_form = DecryptMessage(request.form)
decrypt_form.validate_on_submit()

# Pulling data from form
m = decrypt_form.message_field.data
k = decrypt_form.key_field.data

# Converting private key to bytes
k_bytes = k.encode()

# Generate new key
base64_key = base64.urlsafe_b64encode(k_bytes)
g = Fernet(base64_key)

# Decrypt message
decrypt_message = g.decrypt(m)
final_output = decrypt_message

return render_template('decrypted.html', final_output=final_output)
alpine socket
#

yes...hopefully ๐Ÿคž

primal sinew
#

Now I am getting error message ValueError: Fernet key must be 32 url-safe base64-encoded bytes.

alpine socket
#

try the base64.b32encode()

#

@primal sinew

primal sinew
#

@alpine socket No sorry. Still not working. I have even tried ```python
base64_key = base64.urlsafe_b64encode(k_bytes[:32])

#

I appreciate your help by the way. ๐Ÿ˜ƒ

alpine socket
#

base64.urlsafe_b64encode() should work...but i dunno

#

no problem ๐Ÿ˜ธ

#

the value eroor is at which line?

primal sinew
#

Line 37 which is this ```python
base64_key = base64.urlsafe_b64encode(k_bytes)

primal sinew
#

I have just tried this in all in IDLE and it looks OK to me. ๐Ÿ˜ฆ

primal sinew
#

OK I am progressing with this now. Here is the updated code: ```python
@app.route('/decrypted')
def decrypted():
# Registering forms
decrypt_form = DecryptMessage(request.form)
decrypt_form.validate_on_submit()

# Pulling data from form
m = decrypt_form.message_field.data.encode()
k = decrypt_form.key_field.data

# Converting private key to bytes
k_bytes = k.encode()

# Generate new key
base64_key = base64.urlsafe_b64encode(k_bytes [:32])
g = Fernet(base64_key)

# Decrypt message
decrypt_message = g.decrypt(m.decode())
final_output = decrypt_message

return render_template('decrypted.html', final_output=final_output)
#

I think the problem now is passing an already encrypted message to the decrypt function as I now get the error message: TypeError: token must be bytes.

primal sinew
#

So I have since managed to pass the encryption key as bytes using the following code: ```python
@app.route('/decrypted')
def decrypted():
# Registering forms
decrypt_form = DecryptMessage(request.form)
decrypt_form.validate_on_submit()

# Pulling data from form
m = decrypt_form.message_field.data
k = decrypt_form.key_field.data

# Converting private key to bytes
k_bytes = k.encode()

# Generate new key
base64_key = base64.urlsafe_b64encode(k_bytes [:32])
g = Fernet(base64_key.decode(k))

# Decrypt message
decrypt_message = g.decrypt(m)
final_output = bytes.decode(decrypt_message)

return render_template('decrypted.html', final_output=final_output)
#

But I now get the error message: LookupError: unknown encoding: XQ5wNimxc3YdO3set1cpbjZq1AT3waC9m1wGV05wB3Y=

alpine socket
#

final_output = decrypt_message.decode()

#

and enter the encoding as a argument encoding="...'

primal sinew
#

@alpine socket Amended code: ```python
@app.route('/decrypted')
def decrypted():
# Registering forms
decrypt_form = DecryptMessage(request.form)
decrypt_form.validate_on_submit()

# Pulling data from form
m = decrypt_form.message_field.data
k = decrypt_form.key_field.data

# Converting private key to bytes
k_bytes = k.encode()

# Generate new key
base64_key = base64.urlsafe_b64encode(k_bytes [:32])
g = Fernet(base64_key.decode(k))

# Decrypt message
decrypt_message = g.decrypt(m)
final_output = decrypt_message.decode(encoding='ASCII')

return render_template('decrypted.html', final_output=final_output)
alpine socket
#

working? @primal sinew

primal sinew
#

Nope still the same error message sorry @alpine socket

#

Do I need to specify the encryption method?

alpine socket
#

i think the error might be in the line
g = Fernet(base64_key.decode(k))

primal sinew
#

Yes I think you're right.

alpine socket
#

because i think the decode func does not any arguments

primal sinew
#

Removed the argument and now have TypeError: argument should be a bytes-like object or ASCII string, not 'builtin_function_or_method'

alpine socket
#

oops

#

what is entered in k?

primal sinew
#

It's a generated key that has been converted to a string. Basically I want someone to encrypt a message and send on details and be able to decrypt.

#

So the user would input the encrypted message and the private key and it would output the message in plain text.

#

If that makes sense! yoj

outer marsh
#

Goood morning awesome people, I am looking for some direction to improve the performance of this chunk of code.

        if(ats_unts != "0"):
            q = q.filter(unit_id=ats_unts)

        if (res_status == "1"):
            q = q.filter(ResultsID="PASSED")

        if (res_status == "2"):
            q = q.filter(ResultsID="FAILED")


        q = q.filter(fixed_start_date__gte=start_date)
        q = q.filter(fixed_start_date__lte=end_date)
        q = q.filter(fixed_start_time__gte=start_time)
        q = q.filter(fixed_start_time__lte=end_time)
        q = q.order_by('-StartTime')[:1000]```

Currently this takes forever to run, is there a better way to handle user filtering? Python 3.7, Django 2.1.1 

Just need to be pointed in the right direction. ๐Ÿ˜„ Thanks!
surreal thicket
#

does django automatically combine filters like that?

#

you might be running a lot of nested subqueries, which your db engine might or might not be able to optimize

#

however you need to say:

  • what database engine
  • what part is slow (the db query, or something else)
  • how big is the table
  • how big is the result set
  • do you have any indices on the table
  • what is the cardinality of said indices
  • what is your definition of "slow"
#

@outer marsh

cinder path
#

Sorry to but in but is there any way to make <pre></pre> mobile responsive? My page just hides it being overflown on the x axis.

surreal thicket
#

what do you mean hides?

cinder path
#

sorry if I didn't describe that in the best way

surreal thicket
#

<code>

#

i think should fix it

#

instead of <pre>

#

ah wait dont use code outside pre

#

hang on

cinder path
#

yea that breaks the spaces

surreal thicket
#

<pre><code> first of all

#

for semantic purposes

cinder path
#

problem with code right

surreal thicket
#

and you cant scroll that horizontally?

cinder path
#

is I have a css that gives it a coloured background

surreal thicket
#

i think you just dont get a scroll bar on mobile (i dont on iOS)

cinder path
#

so it is in lines

surreal thicket
#

you should still be able to scroll that horizontally

cinder path
#

I skipped that via a div with a class

#
      <div class="codeblock">
        <pre>
&lt;!DOCTYPE html&gt;
&lt;html lang="en" dir="ltr"&gt;
  &lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;Profile&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;p&gt;Hello this is my profile page!&lt;/p&gt;
  &lt;/body&gt;
&lt;/html&gt;</pre>
      </div>
#
.codeblock {
  background-color: rgba(45, 202, 255, .2);
  border-radius: 0.25rem;
  margin: 1em 0 1em 0;
  padding: 1em;
}
surreal thicket
cinder path
#

shall I add that to the div since I want the rest of my content to fit onto the page

surreal thicket
#

yes

#

not 100% thats the right answer but try it

cinder path
#

that doesn't work

#

so its working on mobile view which is nice to know

#

but stops at 374px

#

in browser

cinder path
#

Sorted!

outer marsh
#

@surreal thicket I have kind of shifted gears since i asked this question earlier. The table in question is 41k rows, and im using sqlite. I have been preparing to migrate to MySQL - so now i am looking at a way to move the data .

surreal thicket
#

that is harder. personally, i would load the sqlite data into pandas and write into mysql

#

41k rows is not that big

outer marsh
#

stellar that gives me a direction! thank you!

#

This wont probably fix my filtering issue - but the migration needs to happen so better now than later.

surreal thicket
#

honestly that data set is small enough you can just load it in memory and do filtering in pandas ๐Ÿ˜„

fast narwhal
#

hey

#

anyone here know django

#

my problem is that im trying to run "python manage.py migrate" but im getting this error "django.db.utils.IntegrityError: NOT NULL constraint failed: polls_comment.user_id"

patent cobalt
#

Did you run makemigrations for your app?

fast narwhal
#

yes

#

i did

candid gust
#

hey, also a django question. how can I make an app 'global', so I can add it to INSTALLED_APPS without explicitly having the app in my project directory?

quick trench
#

Hello,
I am building an rest app with flask using connexion and swagger.
I needed a custom sql wrapper for postgres so I tried attempting a extension for that based on example code on flask ext dev, but the passing app to init_app() results in not initializing the app.
Has anyone attempted anything like this?

primal sinew
#

Morning people. Still having issues with this. I have tested this in a python terminal and everything works OK so not sure if I am missing something? Here is the code: ```python
@app.route('/decrypted')
def decrypted():
# Registering forms
decrypt_form = DecryptMessage(request.form)
decrypt_form.validate_on_submit()

# Pulling data from form
m = decrypt_form.message_field.data
k = decrypt_form.key_field.data

# Converting data to bytes
m_bytes = m.encode(encoding='utf-8')
k_bytes = k.encode(encoding='utf-8')

# Generate new key
base64_key = base64.urlsafe_b64encode(k_bytes [:32])
g = Fernet(base64_key)

# Decrypt message
decrypt_message = g.decrypt(m_bytes)
final_output = decrypt_message.decode()

return render_template('decrypted.html', final_output=final_output)
#

I get the following error message cryptography.fernet.InvalidToken

primal sinew
#

Anyone?

alpine socket
#

Haven't figured it out yet?

#

Try removing the [:32]

primal sinew
#

No I have been trying the majority of last night and this morning. Looked through countless Stack and Reddit posts and still no joy.

#

I do believe I have tried removing the 32 previously and still had the same issue.

#

Removing that part of the code produces this error. ValueError: Fernet key must be 32 url-safe base64-encoded bytes.

#

There is obviously an issue turning the key from string format into bytes so that it can be used to decrypt the message.

eager sorrel
#

Is this where I should be asking about web scraping?

#

or is there a better room

tardy pasture
#

@eager sorrel I would be more inclined to ask web scraping questions in one of the generic help channels, but... what's the question?

eager sorrel
#

Ah I already asked In the help channels, thanks though

rare oar
#

Hey all, apparently my google is failing me. In Django, if I want to .get an object where a m2m contains all elements exactly, how does that work?
MyModel.objects.get(some_m2m=?)

#

Is it a list of ids? List of objects? It keeps saying like it should be a an int or something

#

Full context

#
class Team(models.Model):
    name = models.CharField(default='Random Team', max_length=300)
    team_avatar = models.URLField()
    players = models.ManyToManyField('Player', unique=True)



class Roster(models.Model):
    match = models.ForeignKey('Match', on_delete=models.CASCADE, related_name='rosters')
    player = models.ForeignKey('Player', on_delete=models.CASCADE, related_name='rosters')
    team_number = models.IntegerField(blank=True, null=True)
    slot_number = models.IntegerField(blank=True, null=True)

    class Meta:
        unique_together = ('match', 'team_number', 'slot_number')

    def __str__(self):
        return f"{self.player.display_name}: Team: {self.team_number} Slot: {self.slot_number}"


class Match(models.Model):
    created = models.DateTimeField(auto_created=True, auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(choices=STATUS_CHOICES, max_length=300, default='in progress')
    players = models.ManyToManyField(Player, through='Roster', related_name='matches')


    def __str__(self):
        return f"Match on {self.created}"

    def get_team(self, team_number: int) -> Optional[Team]:
        # How best to do this? Code throws error.
        player_ids = [r.player.id for r in Roster.objects.filter(team_number=team_number)]
        return Team.objects.get(players=player_ids)
#

Thoughts behind the setup to have Match have players as m2m be so I can associate teams and slot position of player. Really in perfect world would just be a m2m on Team but I don't know how I would record slot_ids per match unless I make that its own m2m.... which I guess is possible?

native tide
#

ive been trying to get a page to redirect a user when he registers an acc in the site

#

here is the function in views.py

#

can someone help please, its not redirecting

steel tiger
#

how hard is it to implament basic encryption into flask + sqalchemy?

#

just save password as a hash and hash users attemted password and see if it matches

#

with the salting things

meager anchor
#

hard? not at all

#

check out hashlib

kindred gate
#

okay so I'm an idiot

#

basically I'm using a module called Quart

#

which is esentially just asynchronous Flask

#

and am trying to put subdomains in

#

but it won't work

#

bp = Blueprint("main", __name__,subdomain="main")

#

that's how the blueprint is initialized

#
127.0.1.1 main.suhails-vps.localdomain suhails-vps
#

and that's my hosts file (I read online somewhere that I had to change it)

#

However I get this error:

#
    run()
  File "/var/www/new-spyke/assets/py/__init__.py", line 14, in run
    load_blueprints(app)
  File "/var/www/new-spyke/assets/py/__init__.py", line 25, in load_blueprints
    app.register_blueprint(blueprint)               
  File "/root/.pyenv/versions/3.6.5/lib/python3.6/site-packages/quart/app.py", line 1169, in register_blueprint
    blueprint.register(self, first_registration, url_prefix=url_prefix)
  File "/root/.pyenv/versions/3.6.5/lib/python3.6/site-packages/quart/blueprints.py", line 678, in register
    func(state)
  File "/root/.pyenv/versions/3.6.5/lib/python3.6/site-packages/quart/blueprints.py", line 120, in <lambda>
    strict_slashes=strict_slashes,
  File "/root/.pyenv/versions/3.6.5/lib/python3.6/site-packages/quart/blueprints.py", line 742, in add_url_rule
    strict_slashes=strict_slashes,
  File "/root/.pyenv/versions/3.6.5/lib/python3.6/site-packages/quart/app.py", line 454, in add_url_rule
    raise RuntimeError('Cannot use host or subdomain without host matching enabled.')
RuntimeError: Cannot use host or subdomain without host matching enabled.
#

if someone can @ me

kindred gate
#

Anyone?

midnight kernel
#

@kindred gate I dont use blueprints, but I do use flask at work every day.

#

When you use blueprints, do you initialize a flask/quart app above the blueprint?

#

like if I wanted to enable host matching, instead of app = Flask(__name__) id have to do app = Flask(__name__, host_matching=True)

kindred gate
#

Okay cool

#

@midnight kernel thanks so much

#

now i get another error

midnight kernel
#

watcha got?

kindred gate
#
    run()
  File "/var/www/new-spyke/assets/py/__init__.py", line 13, in run
    host_matching=True)
  File "/root/.pyenv/versions/3.6.5/lib/python3.6/site-packages/quart/app.py", line 182, in __init__
    'static_host must be set if there is a static folder and host_matching is '
ValueError: static_host must be set if there is a static folder and host_matching is enabled
#

i assume static_host is another kwarg that i need when initing the app

#

but what should it be?

#

@midnight kernel

midnight kernel
#

hmm

#

what do you use in your static folder?

#

i use flask to build REST apis so the templates and static folder i have little experience in

kindred gate
#

i have JavaScript files, CSS files and images

midnight kernel
#

well

#

i think the static host is just like, whatever your base url is

kindred gate
#

hmm]

#

i'll just experiment

midnight kernel
#

or at least whatever is hosting the static folder

kindred gate
#

@midnight kernel I tried and now everything gives me 404 errrors

midnight kernel
#

its probably being directed to the wrong place

kindred gate
#

i don't know how to change it though

#

everything worked fine before the subdomain change

distant plover
#

is there a way to wrap all http errors in flask?

#

(without a gore solution)

sinful pulsar
#

So my django backend successfully manage to handle 170k+ real time users, I almost can't believe django can handle it.

cerulean mauve
#

that's awesome @sinful pulsar . I'm jut learning Django, great to see that it scales so effectively

sinful pulsar
#

@cerulean mauve good luck!

#

One of the biggest thing to consider when deploying django app is to make sure to choose your Gunicorn workers design wisely. Because it will also affect how you handle db connections.

It doesn't give me any problem until I start receiving 30k+ real time users

#

I am still learning about this though

cerulean mauve
#

My current objective is to create a functioning page, so the challenges that will come with scaling are a bit further down the line! ha ha. But it's definetly good to know. I'm excited about the possibilities I'm seeing opening up as I learn.

coral ridge
#

Hey, I got a responsive d3 graph that uses element.clientWidthand element.clientHeight for resizing. However, the clientHeightreturns 0 unless I have this CSS in place:

.graph {
            position: absolute;
            left: 0px;
            right: 0px;
            top: 0px;
            bottom: 0px;
            margin: 0px;
        }
#

This works fine but if I want to add something else to the page, like a dropdown menu, it overlaps with the graph due to that CSS

#

Any ideas for a fix?

coral ridge
native tide
#

What should i use to make a dynamic website, only python would be enough?

#

PHP?

#

and what sort of database should i use as well

#

i'm kinda new into web development stuff, will be helpful if you guys could link me to something where i could learn everything about this area.

cerulean mauve
hollow flower
#

[Flask-Restful & Flask-sqlalhemy]: Umm, how do execute an database update? The documentation only has information how to do select, insert and delete.

rare oar
#

Hi guys still looking for some advice on setting up django models

#

I've written up some history

fast narwhal
#

Im trying to add commenting to my site in django. Right now I:'m getting this error "type object 'Poll' has no attribute 'get_absolute_url'"
any ideas on how to fix it

jade egret
#

can you link to the docs? or reference where you've seen get_absolute_url used

fast narwhal
#

i was looking at this indivdual video

#

it talks about get abosolute url near the end

jade egret
#

there it is a Post rather than a Poll

fast narwhal
#

yeah because out code is different

#

im using polls hes doing blog posts

jade egret
#

@fast narwhal

rare oar
#

hey guys, trying to get rid of a n+1 problem... I know its select_related or prefetch_related but I guess I can't visualize it. Plugging in random ones with no affect (or even increasing query size).

#

Code:

#

Evaluating like [t.num_wins() fro Team.objects.all()]

quartz idol
#

Where would you guys recommend to start learning HTML and CSS? I want to start learning basic web development.

brave mantle
#

Some friends of mine have had some success with htmldog

fallow cypress
#

i started with freecodecamp

marble pulsar
#

Oh howwould I create my own webhook listener server

#

I'm using python Flask that is listening on port for POST requests

#

And I'm exposing that port to web by using ngrok

#

I'm pretty sure this isn't the best way

steel tiger
#

how to make wtforms actully pass to flask

#

its just appending at end of url for some reason

#

even with <form method="POST"></form>

burnt silo
#

Anyone who can help with viewing flask from an external ip / different host than localhost?

#

have tried app.run(host='0.0.0.0', port=3000)

marble pulsar
#

@burnt silo same prob, hope we figure it out

coral ridge
#

That should work

#

Might need to do some port forwarding

#

But you should be able to access it inside your local network

coral ridge
#

Something to keep in mind is to include the port :D I've made that mistake too many times trying to access 192.168.0.1 without :5000 at the end

lofty cargo
#

Hi, i want to ask something.
Im trying to deploy flask app to ubuntu server. I connected with ssh and following tutorial for deploy. There is apache on server and already running with 80 port for another php project. Tutorial steps telling me that create apache conf as follows.

        ServerName yourdomain.com
        ServerAdmin admin@yourdomain.com
        WSGIScriptAlias / /var/www/Flask/flaskapp.wsgi
        <Directory /var/www/Flask/Flask/>
            Order allow,deny
            Allow from all
        </Directory>
        Alias /static /var/www/Flask/Flask/static
        <Directory /var/www/Flask/Flask/static/>
            Order allow,deny
            Allow from all
        </Directory>
        ErrorLog ${APACHE_LOG_DIR}/error.log
        LogLevel warn
        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>```
if im creating file like this, will it not be problem for the project already running on apache?
hollow flower
#

Umm, how would I get this to work?

#
from flask import request
from flask_restful import Resource
from models import db, Discord_Users


class UsersResource(Resource):
    def get(self):
        value = request.args.get('user_id')
        if value is not None:
            query = db.session.query(Discord_Users.user_id, Discord_Users.permission_granted) \
                .filter(Discord_Users.user_id == value) \
                .one()
            return {'status': 'success', 'data': query}, 200
        else:
            return {'status': 'failed', 'message': 'This is not how it works'}, 400
hollow flower
#

Can someone help me out?

unkempt wharf
#

Instead of from flask_restful import Resource do from flask_restful import Resource, Api

#

Right under the import statements do app = Flask(__name__)

#

api = Api(app)

#

Under the class add api.add_resource(UsersResource, '/') if __name__ == '__main__': app.run(debug=True)

frigid furnace
#

Does anyone run into problem with django imports?

hollow flower
#

@unkempt wharf No, as I have this.

Filename is app.py:

from flask import Blueprint
from flask_restful import Api
from resources.Hello import Hello
from resources.Messages import MessageResource
from resources.Messages import CountMessages
from resources.Messages import CountMessagesByChannel
from resources.Profiles import ProfilesResource
from resources.Users import UsersResource

api_bp = Blueprint('api', __name__)
api = Api(api_bp)



# Routes
api.add_resource(Hello, '/Hello')
api.add_resource(MessageResource, '/Messages')
api.add_resource(ProfilesResource, '/Profiles')
api.add_resource(CountMessages, '/UserMessageCount')
api.add_resource(CountMessagesByChannel, '/UserMessageCountByChannels')
api.add_resource(UsersResource, '/Users')
#

Also there is already a traceback, which says: TypeError: Object of type datetime is not JSON serializable.

#

So how do I serialize it?

brittle glacier
#

Hey guys!

I want to host a mini-webshop on my poor Raspberry Pi. It's not supposed to have huge traffic, just some people in a group. I want to store the addresses with Flask, and use the PayPal checkout payment thing.

Is this dangerous?

nimble crow
#
@app.route("/interphore/early/code_here")
def interphore_early():
    return app.send_static_file(
        "/games/latest/interphore/early/code_here/interphore_early_play.html"
    )
#

This is getting annoying

#

it clearly exists but it says it doesn't

kindred gate
#

Any errors in your terminal?

#

Also you're using flask right?

nimble crow
#

And yes I'm using flask

kindred gate
#

What's ur entire code?

nimble crow
#

big

kindred gate
#

Could be due to the fact that you haven't restarted the python file?

nimble crow
#

It restarts when I save it.

kindred gate
#

Do all other parts of your site work?

nimble crow
#

Yup

#

specifically these two don't work

#
@app.route("/interphore/dev/code_here")
def interphore_dev():
    return app.send_static_file(
        "/games/latest/interphore/dev/code_here/interphore_dev_play.html"
    )


@app.route("/interphore/early/code_here")
def interphore_early():
    return app.send_static_file(
        "/games/latest/interphore/early/code_here/interphore_early_play.html"
    )
#

And if it's down to send_static_file, then I don't know how

kindred gate
#

Are those your only two routes with send_static_file

nimble crow
#

Yup

#

And they have to be like that

kindred gate
#

Maybe test it to return "hi" and see if the routing's the issue?

nimble crow
#

Can't send the html from template

#

1 sec

brittle glacier
#

How do I load a new page on Flask

#

Without changing the url

#

Or, do I need to do that lol

kindred gate
#

New page?

nimble crow
kindred gate
#

So it's your static file

nimble crow
#

It's send_static_file

#

I copied the urls exactly in the file system

kindred gate
#

Is the file in your static folder?

nimble crow
#

Yes

#

I just said

#

I copied the url

#

exactly

kindred gate
#

So the file is in static/games/latest...?

nimble crow
#

Once again

#

yes

#

if it wasn't I wouldn't see it

kindred gate
#

The only thing I can think of is that it can't find the file

nimble crow
#

In which case jinja would cause an exception

kindred gate
#

That 404 error is because it can't find the file

#

Nah it raises 404 errors instead

nimble crow
#

:/

quaint ledge
#

did you add https::/ or whatever it is to the front?

nimble crow
#

Why the fuck

#

would you

kindred gate
#

It's localhost that's unlikely

quaint ledge
#

idk thats what worked for me

#

owez sent me a demo and told me to use https

nimble crow
quaint ledge
#

its worth a try if theres no other options

#

ok

kindred gate
#

The only thing I can think of is that the file directory is wrong

quaint ledge
#

sorry

kindred gate
#

If you added the file after the code started running that could cause a problem

#

You might wanna restart the python file and see if that does anything

nimble crow
#

I mean, it restarts when I save

#

and I saved right after making the route

kindred gate
#

The app does but I don't think it grabs any new static files

nimble crow
#

Killed process and started again

#

still no results

kindred gate
#

I'm sorry I have no idea

#

The only thing I can say is double check to ensure your directory is right

nimble crow
#

Which it is

quaint ledge
#

download might be corrupted

#

i had to delete all my d.py files and reinstall it before it started working right

nimble crow
#

Also it works for everything else

#

Just the one fucking time i need to send_static_file

#

it fucking breaks

kindred gate
#

All other static files work, right?

nimble crow
#

Yes

#

Ant they all template

#

These ones

#

I cannot template

#

Which is why I am working with them differently

#

If there is any other way of loading static html from /static

#

I'd love to hear it

#

because this shit doesn't fucking work

kindred gate
#

flask.send_from_directory exists

nimble crow
#

Been there, done that

#

It fucking broke on me

quaint ledge
#

yo ignore me if u want but i think you might be getting kind of heated, you should try taking a break to collect yourself so you can focus on it later.

nimble crow
#

Flask what the fuck is up

kindred gate
#

Try your full directory

nimble crow
#

Still 404

kindred gate
#

try os.path.join(os.getcwd(), "games/latest/...)

#

Import os ofc

nimble crow
#

It's not gonna work

#

I'm calling it now

#

great

kindred gate
#

Have you tried flask.send_file

#

cos there's nothing else I can suggest

nimble crow
#

not that it's anything good

#

I just forgot /static

#

I fucking copied the url

#

exactly

#

and it pulls this shit

kindred gate
#

Try printing app.root_path

#

is it where you expect?

nimble crow
#

C:\Users\Paws\Desktop\paraphore

#

so yes

#

it very much is

#

Never mind, the person I was making this for decided to fucking call it off

kindred gate
#

oof

nimble crow
#

I'm fucking done.

red finch
#

Hey at school there was recently a subject you could choose called Information technology i decided to choose the subject and right now we are learning html and css

#

im kinda ahead of the group and i was wondering what cool stuff i could do on the website

#

i have the background as a gif, ive learned to play mp4 files and videos, ive got headings, subheads and dot points

#

ive also done links and images

hollow flower
#

Look into javascript.

red finch
#

@hollow flower can i ask, what can i do with javascript on my website, the teacher said we will be learning that later, but i am down to get a headstart

hollow flower
#

To be quite honest, a lot of things. The loading on my website for example is done with javascript. (https://samip.fi)

red finch
#

and what about when i click the button and it scrolls down

hollow flower
#

That's CSS transition.

red finch
#

any links to that?

#

where i can learn it

hollow flower
red finch
#

ahh

#

im learning that rn

#

working through it ๐Ÿ˜„

#

thankyou ill give it a go

hollow flower
#

No problem. The HTML & CSS3 course can be boring at times, at least it was for me. :)

split copper
#

I made a Dungeon Generator in python that takes some input from the user (a seed, size, etc) and returns an image. I would like to make a single page website that would run the script but have no idea how to go about doing that. Any pointers on picking a framework or useful tutorials on how to set it up?
Some people recommended Django but I'm overwhelmed just looking at it, no idea where to start or what to do to make this happen.

Thanks!

shut parcel
ivory crest
#

Flask and Django are both fine for beginners in my opinion, it's just that Django looks more intimidating because it throws everything at you at once whereas Flask you have to assemble yourself so you get a feel for it as you go but if you just start with the Django beginner tutorial it breaks it down into smaller more manageable pieces to learn, just as the flask mega tutorial does.

sullen gyro
#

Hello everyone,

fast narwhal
#

hi

#

i have a problem in my code, im using django.. im trying to implement comments but im getting the error "'Poll' object has no attribute 'get_absolute_url'"

#

heres my code

#
@login_required
def poll_detail(request, poll_id):
    #poll = Poll.objects.get(id=poll_id)
    poll = get_object_or_404(Poll, id=poll_id)
    comments = Comment.objects.filter(post=poll).order_by('id')
    user_can_vote = poll.user_can_vote(request.user)
    results = poll.get_results_dict()

    if request.method == "POST":
        comment_form = CommentForm(request.POST or None)
        if comment_form.is_valid():
            text = request.POST.get('text')
            comment = Comment.objects.create(post=poll, user=request.user, text=text)
            comment.save()
            return HttpResponseRedirect(poll.get_absolute_url())

    else:
        comment_form = CommentForm()

    context = {
        'poll': poll,
        'user_can_vote': user_can_vote,
        'results': results,
        'comments': comments,
        'comment_form': comment_form
    }
    return render(request, 'polls/poll_detail.html', context)
sullen gyro
#

why dont you try reverse() function and see if it fixes the issue

calm garnet
#

Hey, I am going to build a site however, I have 2.4TB database with sqllite to host. This is expecting to grow 10% a year. Anyone help me out with what type of requirements it would take if I were to use a cloud service?

hollow flower
#

Umm, switch to a better database backend.

#

I don't even know how sqlite likes that big of a database.

calm garnet
#

So the data I need is already done inside a database. Iโ€™m just downloading it and then updating it monthly with the new data, the website is going to query the data

#

I donโ€™t think I could move the data to new database easily anyways

hollow flower
#

So do you plan on hosting the site with the large database in the cloud?

hollow flower
#
from flask import request
from flask_restful import Resource
from models import db, Discord_Users


class UsersResource(Resource):
    def get(self):
        value = request.args.get('user_id')
        if value is not None:
            query = db.session.query(Discord_Users.user_id, Discord_Users.permission_granted) \
                .filter(Discord_Users.user_id == value) \
                .one()
            return {'status': 'success', 'data': query}, 200
        else:
            return {'status': 'failed', 'message': 'This is not how it works'}, 400

How do I fix the error as it says: TypeError: Object of type datetime is not JSON serializable?

kindred gate
#

Does your query have a datetime in it?

hollow flower
#

Yes.

kindred gate
#

That's probably why

hollow flower
#

Discord_Users.permission_granted has a datetime in it.

#

And I want to output that datetime too, but in json.

kindred gate
#

You might need to pass through your query and turn that datetime into a string

#

You can't output a datetime and a lot of other models via JSON

hollow flower
#

Hmm, then how would I get the same kind of json layout when using that {'status': 'success', 'data': query}, 200 if I were to use jsonify?

kindred gate
#

Is query a dictionary right?

hollow flower
#

No.

#

It's <class 'sqlalchemy.util._collections.result'>

#

@kindred gate

sweet wharf
#

Can someone help me connect ReactJS to Django?

tardy pasture
#

What have you tried and what problem are you encountering?

#

@sweet wharf

sweet wharf
#

especially nodeJS problems

#

but i think i will try to use rest_framework even though i dont understand it yet

tardy pasture
#

I'd definitely recommend separating things, like so: #004990

#

Er

#

One sec

#

Like that.

#

There's two schools of thoughts on getting started - you could start with React and then make a dummy API for mocking data, and then model your API on the dummy API

#

Or you can make the API first.

#

How much experience do you have with consuming / using APIs?

red finch
#

is there a way to get my links not to underline

steel tiger
hollow flower
#

Hmm, I'm myself among those who use Flask. :D

sturdy sapphire
#

!warn 390556291766157323 please keep the help channels on topic

lavish prismBOT
#

:incoming_envelope: :ok_hand: warned @quasi wedge (please keep the help channels on topic).

brave mantle
#

That took a while

sturdy sapphire
#

yes python is a bit slow today. We have top men working on it

brave mantle
#

Needs more hamsters!

hollow flower
#

Is it a good idea to switch from flask_restful to flask_restplus?

hollow flower
#

If I want to use flask_restplus with swagger documentation, how do I specify them to my resource classes?

#

How do I set the definition?

steel tiger
#

may be useful

#

(generating a decent flask application structure)

dull ginkgo
#

is there a way to do a text box in css

primal flicker
#

are there any free recent tutorials on building APIs with flask?

#

I want to integrate my react frontend with a flask backend for CRUD'ing a database

modern acorn
#

@dull ginkgo textbox in CSS? You mean styling a textarea element?

quiet solstice
#

@sweet wharf are you sure you imported it correctly

sweet wharf
#
import React, {Component} from 'react';
import ReactDOM from "react-dom";

const app = document.getElementById('app');

class App extends Component {
    render() {
        console.log(ReactDOM)
        return <h1>React App</h1>
    }
}
ReactDOM.render(<App />, app);```
#

this is the code im trying to run

#

i tried importing ReactDom but i get the same error

quiet solstice
#

can you log the reactdom before the render

sweet wharf
#

I tried that aswell but i get the same error. it wont log

quiet solstice
#

and you did rebuild after making the changes?

#

and is react-dom defined correctly in the webpack config

sweet wharf
#

I did not build the project yet. I use "dev": "webpack --mode development ./frontend/src/index.js --output ./frontend/static/frontend/main.js", command

#
module.exports = {
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            }
        ]
    }
}```this is my wp config
#

wait nevermind i feel soo stupid now

#

thx for you time anyways

quiet solstice
#

what was the fix?

sweet wharf
#

I forgot to put --watch in the script so i needed to reload everytime i made a change in the js file

dull ginkgo
#

how do i make text in an input box bigger

ivory pagoda
#

css:
style="font-size: 24px;"

dull ginkgo
#

thank you!! @ivory pagoda

native tide
#

Hey anyone know why when I make an input thing it puts the box then the text

#

I want it like (text) ( then enter box) but it does the opposite

#

tag me if u respond so I know someone answered plz

opal leaf
#

what html are you using and what css do you have? why its happening can vary wildly because of that stuff @native tide

#

might want to use the web browsers inspector to see what css and such is impacting your components

native tide
opal leaf
#

so its likely due to whatever css you have

native tide
#

Thats the only css that would be effecting the container

opal leaf
#

is that all of your css or are you using something like bootstrap that adds a ton of defaults?

#

sometimes they are set up in a way that requires you to use a specific tag for input labels

native tide
#

that isnt all that is all that would be effecting the container here ill send a pic of all

opal leaf
#

id prefer it in text form tbh so i can copy paste and test stuff

kind steppe
#

@native tide sorry about that

#

you triggered our newlines rule

native tide
#

srry my b ok

#

I just dont see anything that would make it flip out like that on my page.

opal leaf
native tide
#

oooooo I didnt add a break after one of them and I thought it was puttting it first

#

my apology

#

thank u tho

opal leaf
#

haha no worries

steel tiger
#

i always need to add css .container { padding-top: 15px; }

#

when dealing with bootswatch because text gets too close to navbar for comfort

hot robin
#

is there way to get a context variable with something like {{ user + i }} where i is a variable in a for loop

#

and user is part of the context

opal leaf
#

some web frameworks have a built in way to manage a 'list' of items in a form that all have the same name

hot robin
#

oops probably should have managed its django

#

anything more specific to django like that or not sure? ive been looking around

opal leaf
#

hm ill have to look at the documentation to see

#

i have really only used flask

hot robin
#

alright. ill do some digging in the docs

opal leaf
#

looks like people are suggesting that you instead use a dict or list

#

rather than naming them all similar stuff

#

and then the templates have a built in looping system that you can use

hot robin
#

ty

#

I was looking at a dict as the first thing but i didnt know thatd work

#

but ill take a look

#

that actually might be exactly what im looking for. thanks!

opal leaf
#

:>

hot robin
#

yeah it was dot notation in a template but i thought of the normal way with like key[value]

#

so that clears a lot up lol

hollow flower
#

If my project structure is like this:

.
โ”œโ”€โ”€ app
โ”‚ย ย  โ”œโ”€โ”€ __init__.py
โ”‚ย ย  โ”œโ”€โ”€ main
โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ config.py
โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ controller
โ”‚ย ย  โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ api_user_controller.py
โ”‚ย ย  โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ auth_controller.py
โ”‚ย ย  โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ discord_users_controller.py
โ”‚ย ย  โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ hello_controller.py
โ”‚ย ย  โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ __init__.py
โ”‚ย ย  โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ messages_controller.py
โ”‚ย ย  โ”‚ย ย  โ”‚ย ย  โ””โ”€โ”€ profiles_controller.py
โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ flask_boilerplate_main.db
โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ flask_boilerplate_test.db
โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ __init__.py
โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ model
โ”‚ย ย  โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ api_users.py
โ”‚ย ย  โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ blacklist.py
โ”‚ย ย  โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ channels.py
โ”‚ย ย  โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ discord_users.py
โ”‚ย ย  โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ __init__.py
โ”‚ย ย  โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ messages.py
โ”‚ย ย  โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ profiles.py
โ”‚ย ย  โ”‚ย ย  โ”‚ย ย  โ””โ”€โ”€ users.py
โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ service
โ”‚ย ย  โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ api_user_service.py
โ”‚ย ย  โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ auth_helper.py
โ”‚ย ย  โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ blacklist_service.py
โ”‚ย ย  โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ discord_users_service.py
โ”‚ย ย  โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ __init__.py
โ”‚ย ย  โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ messages_service.py
โ”‚ย ย  โ”‚ย ย  โ”‚ย ย  โ””โ”€โ”€ profiles_service.py
โ”‚ย ย  โ”‚ย ย  โ””โ”€โ”€ util
โ”‚ย ย  โ”‚ย ย      โ”œโ”€โ”€ decorator.py
โ”‚ย ย  โ”‚ย ย      โ”œโ”€โ”€ dto.py
โ”‚ย ย  โ”‚ย ย      โ””โ”€โ”€ __init__.py
โ”‚ย ย  โ””โ”€โ”€ test
โ”‚ย ย      โ”œโ”€โ”€ base.py
โ”‚ย ย      โ”œโ”€โ”€ __init__.py
โ”‚ย ย      โ”œโ”€โ”€ test_auth.py
โ”‚ย ย      โ”œโ”€โ”€ test_config.py
โ”‚ย ย      โ””โ”€โ”€ test_user_medol.py
โ”œโ”€โ”€ configs
โ”‚ย ย  โ”œโ”€โ”€ app.ini
โ”‚ย ย  โ””โ”€โ”€ test.ini
โ”œโ”€โ”€ Dockerfile
โ”œโ”€โ”€ Makefile
โ”œโ”€โ”€ manage.py
โ”œโ”€โ”€ migrations
โ”‚ย ย  โ”œโ”€โ”€ alembic.ini
โ”‚ย ย  โ”œโ”€โ”€ env.py
โ”‚ย ย  โ”œโ”€โ”€ README
โ”‚ย ย  โ”œโ”€โ”€ script.py.mako
โ”‚ย ย  โ””โ”€โ”€ versions
โ”‚ย ย      โ”œโ”€โ”€ 0b60d1b2676f_more_tables.py
โ”‚ย ย      โ”œโ”€โ”€ 63aa1eb343ec_more_tables.py
โ”‚ย ย      โ””โ”€โ”€ fd6a303ce8d4_initial_database_migration.py
โ”œโ”€โ”€ README.md
โ””โ”€โ”€ requirements.txt
#

what do I set in uwsgi config as callable?

#

cat app/main/init.py:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_bcrypt import Bcrypt

from .config import config_by_name

db = SQLAlchemy()
ma = Marshmallow()
flask_bcrypt = Bcrypt()


def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config_by_name[config_name])
    db.init_app(app)
    flask_bcrypt.init_app(app)

    return app
#

That's the one that should be the callable right?

brave mantle
#

That's not callable

#

Basically uwsgi wants you to give it a module that you can run that will end up with a WSGI app object at module level

#

your create_app isn't being run with the result stored in that module - so it's not correct

#

you could use eg ```py
if name == "main":
app = create_app(...)

#

then refer to your app.__init__:app

I think a lot of projects use an app.py or __main__.py for this though - in which case you'd have either app.app:app (lol) or just app:app respectively

brave mantle
#

@hollow flower

meager anchor
#

i go the django route and create an extra wsgi.py file where i just instantiate the app

brave mantle
#

Ah, yeah, I forgot about that, that's a fairly common approach too

steel tiger
#

does django use pure jinja for templating?

brave mantle
#

It uses the django templating language

#

jinja is kinda inspired by it, so it looks similar, but it's not the same

steel tiger
#

i thought django came after jinja?

brave mantle
#

You can make it use jinja but it's not really advisable

#

Nope

steel tiger
#

huh

#

well my navbar if statement works fine across django and flask so im happy enough with that

brave mantle
#

You should avoid trying to do that with your templates, really

#

Each templating system has its own quirks, and you need to make use of them to get the most out of them

steel tiger
#

how do you make it highlight then

brave mantle
#

in what?

steel tiger
#

navbars

brave mantle
#

with a CSS class?

steel tiger
#

like if im on the about page, make the about highlightd

#

yeah

brave mantle
#

I don't understand your question

steel tiger
#

nvm

#

they both use the exact same request.path thing so it works for me

brave mantle
#

okay, but don't rely on that

#

if you have a flask app and a django app then they should have their own templates :P

steel tiger
#

yeah its only for highlighting the navbar things

brave mantle
#

No, you're missing my point

#

If that changes between versions of either flask or django then it'll break

steel tiger
#

yeah

brave mantle
#

You need to be maintaining the templates separately

steel tiger
#

i done it once on django and ported to flask

brave mantle
#

Also, django and flask don't use the same template inheritance stuff

steel tiger
#

thats the bit i changed

brave mantle
#

You shouldn't be copy-pasting your navbar code into each template, so you need to think about that as well

#

anyway, you get my point

steel tiger
#

huh

#

its on the base.html

#

just checking if you are on a specific url

#

and yeah

hollow flower
#

@meager anchor I don't even know what is the django route as haven't used it.

plain solar
#

If I want to display results of my web scraping code to my website

#

What should I do?

#

Like making a simple web scraping using requests

#

And bs4

#

After that I click a button on my website and it sends a request to my web scraping script and it returns back and shows the results

#

I'm lost lmao, people say use a framework like flask or Django but I think that would be overkill

shrewd sand
#

@olive wharf Sorry to disturb, but is that pfp allowed here? xad

#

See above ,^

olive wharf
#

Think we concluded it was, barely

plain solar
#

@knotty lark if you can answer, I'm sorry to bother you

kind steppe
#

@plain solar going to have to ask you to change your profile picture if you want to remain a member here. It does not comply with our NSFW policy

plain solar
#

@kind steppe Oh okay!

#

I'll do within say 24 hours

#

Alright?

kind steppe
#

I'd rather that be shorter if possible.

brittle copper
#

I'm running to an issue where it seems like django runs what's inside the if clause even though the condition is not met inside the template

#

Anyone knows if this is just the case, like

#

Everything inside the template renders even if it is not meant to be end up in the finale html that is being served

#

@Helpers damn, damn, damn

#

Can't even ping helpers

patent cobalt
#

You're not supposed to be able to ping helpers; people will help when they think they can and/or have time

#

In your case, it would probably help to have code and an example of your data

#

Without that, it's pretty difficult to help

brittle copper
#
{% if entry|after_count !=0 %}
<a href="{% url 'entry' entry_pk=next.pk %}?order={{order}}" class="showall more-data" title="tรผmรผnรผ gรถster">{{entry|after_count}} more entry</a>
{% endif %}```
#

I come from a time when you can ping helper btw

#

Where entry|after_count is 0, I get NoReverseMatch

#

while it shouldn't even try

#

Nevermind, wrote it in a different way

kind steppe
#

@plain solar you have 10 minutes to comply.

plain solar
#

@kind steppe K cool?

kind steppe
#

Thank you

plain solar
#

K

red finch
#

thats my code for my website, if i hover over a button it drops every content

#

in the first picture im hovering over school

#

second im hovering over entertainment

#

third im hovering over games

#

and im also hoping to find an answer on how to align them under the text

#

note im quite new to html and css so im extension in my class and my teacher doesnt help extension kids and its really fucked but.. yeha

red finch
#

ping me if u can help

native tide
#

Itโ€™s all about the stylesheet

#

Your titles arenโ€™t boxed

#

There are lots of open-source flat dropdown-menuโ€™s to check out, check the source by pressing F12 & learn from it

hallow wave
#

how can I create a GET request only using sys and socket?

#

I'll get API key and parameters as program arguments

stone pelican
#

Over HTTP or HTTPS?

hallow wave
#

HTTP

stone pelican
#

Alright, HTTPS would be almost impossible without another module. How do you need to send the API key?

hallow wave
#

what do you mean?

stone pelican
#

Is it in some kind of json, a param, authorization header?

hallow wave
#

I'm making a script which creates a socket and connects to openweathermap, then as program argument I get an API key and city's name

#

then it'll print the info to console

#

well, I assume it's an auth header

stone pelican
#

Can I ask why you didn't use requests or urllib?

hallow wave
#

I can't

#

http://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=b498767252de12f92504d2cca9c3fdc1

#

should look sth like this

stone pelican
#

You can't, for like a challenge?

hallow wave
#

yes

stone pelican
#

I think sending data like "GET http://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=b498767252de12f92504d2cca9c3fdc1\r\n" should suffice

hallow wave
#

though I have to admit that networking is not something I know well

stone pelican
#

Do you know how to create sockets?

hallow wave
#

I've already googled how to create socket and connect to API

#

I've done that, but now I'm stuck here

stone pelican
#

What was the response?

#

Also, can I see your code?

hallow wave
#

let me get sth straight: http://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=b498767252de12f92504d2cca9c3fdc1\r\n is the request itself?

stone pelican
#

Wait, I'm so wrong lol, one sec

hallow wave
#
def create_socket():
    try:
        mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    except socket.error:
        print("Failed to create socket. Exiting...")
        sys.exit()

    print("Socket created!")
    return mySocket
#
def connect_to_api(mySocket, ip_address):
    try:
        mySocket.connect((ip_address, port))
    except socket.error:
        print("Failed to connect to API. Exiting...")
        sys.exit()

    print("Succesfully connected to API!")
    return
#

I started with python like 2 days ago

#

this is sth I've put together from a bunch of examples

stone pelican
#

First, you'll need to get the site's ip,so put the website domain (without http) into socket.getaddrbyhost

hallow wave
#

"api.openweathermap.org"

#

I use this as my ip_address

#

seems to work

stone pelican
#

Oh, maybe it does it automatically. Once, you connect like with ("api.openweathermap.org", 80) (port 80 is always used for http.

hallow wave
#

yes, I've read that somewhere and use it

quiet solstice
#

So 2 things.
You don't need a socket connection, it's done with regular http requests

#

And you should never post your api key anywhere

stone pelican
#

I think what you actually want to send is GET /data/2.5/weather?q=London,uk&APPID=b498767252de12f92504d2cca9c3fdc1\r\n

hallow wave
#

it's a non-functional key

#

dw

#

what does the \r\n mean at the end of request?

#

newline?

stone pelican
#

It's to signify a new line, yeah

quiet solstice
#

requests is a great library for what you are trying to do

hallow wave
#

as I've stated, I mustn't use it

#

sadly

stone pelican
#

Not 100% sure however I'm fairly certain HTTP requires a new line at the end

#

Yeah, it worked. Would you to see the code?

hallow wave
#

sure

stone pelican
hallow wave
#

what does the letter b in front of GET mean?

#

binary?

stone pelican
#

You can only send bytes into a socket. String that start with b aren't strings, but bytes

#

So, yeah

hallow wave
#

I see

#

thanks for the tips! I'll give it some time and try to make it work

stone pelican
#

This is different if you're using python2 though, then you only need to send strings

hallow wave
#

i use 2.7.15

stone pelican
#

Ok, then don't use b, otherwise I think it's the same

hallow wave
#

I see, thank you!

hallow wave
#

I got a bit further (thanks to you), but now I'm getting 400

#

any ideas where the mistake could be?

#

my_api_key stands for my personal key, only the printout is changed

#

at the end of request is \r\n

#

mby the real problem is specific to the page's API?

#

well

#

the problem was that I didn't put GET in front of the request

#

end me

coral ridge
#

We've all been there ๐Ÿ˜„

dusky sluice
#

anyone recommend a good tutorial or online resource in learning django?

frigid egret
sturdy sapphire
#

I ran the tutorial but for me it stops at a Middleware error

frigid egret
#

I did read some of those suggestions as well, got me confused at first.

#

Actually this case has been addressed in the tutorial.

#

So it's not the source of the problem.

sturdy sapphire
#

so.. lets unpack what you have done so far

#

you pip installed everything and then you cloned the git repo? right?

#

@frigid egret

frigid egret
#

Yes

sturdy sapphire
#

then what did you do then?

frigid egret
#

Tried the upload form

sturdy sapphire
#

then you ran the migration and then ran the server?

frigid egret
#

And after making sure it works fine, went straight for /admin

#

Yes, I did run migrations as well

sturdy sapphire
#

uploading worked?

frigid egret
#

Since I still don't know when not to use it, I use it more often than I should XD

#

Yes, uploading on both /polls and /polls/import works fine.

sturdy sapphire
#

I got it running now. works for me at least..

#

so what heppens at admin?

frigid egret
sturdy sapphire
frigid egret
#

Can you send me your project so I can try and run it?

sturdy sapphire
#

how do you start the server? from where

frigid egret
#

terminal

sturdy sapphire
#

you liked a folder structure earlier, is that something you use?

frigid egret
#

py manage.py runserver

sturdy sapphire
#

from django-excel ?

frigid egret
#

Yes

#

Yes, from django-excel

sturdy sapphire
#

i did some changes there

frigid egret
#

Uh, the whole file? It's quite long for direct text.

#

Can't upload it as a file. I guess role restrictions.

sturdy sapphire
#

no from instaslled_apps to root_URL

frigid egret
#

wait, hold on

#

Wrong one

#
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'polls'
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware'
)


ROOT_URLCONF = 'mysite.urls'```
sturdy sapphire
#

ahh.. I was about to say so

#

There was a change with MIDDLEWARE_CLASSES some time ago, so when I thought you where using an older version I added this

#

Im sure you just need to rename it to MIDDLEWARE

#

you might have to run the migration again

#

so change that and run try to access the admin page

#

@frigid egret

frigid egret
#

trying rn

#

Yay, it works!

#

Thank you!

#

Is it because I was using a different version?

sturdy sapphire
#

yes, version conflict with the tutorial

#

it was as I suspected from the beginning, but I have limited experience with django so I had to "figure" the solution out myself.

#

glad it works for you @frigid egret

wraith trench
#

Hello, I have issues with django app using django rest framework, specifically with unicode characters error while trying to save request_data to database.
While in request headers there's no unicode characters, it saves it just fine, but if it has one unicode characters postgres psycopg2 throws error
DataError: invalid input syntax for type json - DETAIL: Unicode low surrogate must follow a high surrogate.

Serializer

class DecisionSerializer(serializers.HyperlinkedModelSerializer):
    headers = serializers.DictField(required=False)

    class Meta:
        model = Decision
        write_only_fields = ('headers',)
        fields = ('headers',)

    def create(self, validated_data: dict) -> Decision:
        site = validated_data['site']

        request_data = self.context['request'].data


    site.decision_set.create(allow=False, request_data=request_data)

Model

class Decision(models.Model):
    request_data = JSONField(default=dict)

Settings.py Django rest framework settings

    'UNICODE_JSON': False,
    'STRICT_JSON': True

I'm lost because it should not allow any unicode characters to pass through, but still they got past my settings and throws DataError.

minor zenith
#

so i ve made a script using sendgrid Api
i ve created a django app
i ve created a form in that
i want that it takes values from form
and put that in the script
and run that on submit buttonhanks in advance

ocean kiln
#

What's wrong with this?

#

var fbutton = document.evaluate("//input[@type = 'submit']", document, null, XPathResult.ANY_TYPE, null);
document.fbutton.submit();

red finch
#
/* Style The Dropdown Button */
.dropbtn {

  margin-right: 300px;
  background: transparent;
  color: #ff2a7c;
  padding: 16px;
  font-size: 30px;
  border: none;
  cursor: pointer;
}

/* The container <div> - needed to position the dropdown content */
.dropdown {
  position: relative;
  display: inline-block;
}

/* Dropdown Content (Hidden by Default) */
.dropdown-content {
  display: none;
  position: absolute;
  background: transparent;
  min-width: 107px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

/* Links inside the dropdown */
.dropdown-content a {
  max-width: 30px;
  text-align: right;
  color: #ff2a7c;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

/* Change color of dropdown links on hover */
.dropdown-content a:hover {
    color: #5deadc
}

/* Show the dropdown menu on hover */
.dropdown:hover .dropdown-content {
  display: block;
}

/* Change the background color of the dropdown button when the dropdown content is shown */
.dropdown:hover .dropbtn {
  background: transparent;
}
#

my container seems to be too far open and i cant get it lined up with school

#

if i do <p align='left'</p> it aligns but then its not inside the header

#

and if i do max-width it cuts off from the right hand side

#

please ping if you can help me

outer marsh
#

Does anybody have a good non video tutorial for a database efficient way to sort and search a large table? It can be fairly technical, as anything I don't know in the article I'll just go learn. Just been stuck for a few days. Python 3.6, Django 2., MySQL.

Cross posted in the database channel as well. If there is a better place than here to ask this question, please let me know. Thank you.

glacial quartz
#

@outer marsh i think best database efficeient way is to make some store procedure and call it

lean night
#

Hi, how to receive data of post request in flask?

modern acorn
#

I have a search bar on my website, is there some way to automatically input data into that search bar if the user starts typing even if the search bar isnt selected

#

just jquery or something?

#

Solved it, ty for help

glacial quartz
#

hmm, i want to make gameserwer , my plan was to put it behind ngnix, 1.AuthRegFlask , 2.AdminLobyMatchmakingFlask ,3.Have multypele insances of Websocket games (probbaly in C++)/or can do Flask-SocketIO, so my main question is can i dynamicly change Ngnix rev proxy to target my GameInsances from "AdminLobyMatchmakingFlask" ?

rich panther
#

im on step 4 running gunicorn --bind 0.0.0.0:5000 wsgi:app and receive ImportError: cannot import name 'app'

#

my directory is called mysite and I have the file site.py and wsgi.py. Inside wsgi.py I have from site import app

floral fulcrum
#

trying to use request to load a page that works in chrome but I can't connect in requests

#

requests.exceptions.ConnectionError: ('Connection aborted.', TimeoutError(10060, 'A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond', None, 10060, None)) Anyone have any idea what kind of things I need to look into to set it up

coral ridge
#

What does your code look like? @floral fulcrum

floral fulcrum
#

think there are some networking issues but I am not very familiar with networking

floral fulcrum
#

Oh I figured it out

#

I have to use a different SSL protocol to connect and requests doesn't do that automatically

fossil lotus
#

New to webdev but other than sqlite what other ways could I store data that python can access?

floral fulcrum
#

sqlite is only one of many different kinds of databases and python can access data in many ways

#

it depends on what you are doing

fossil lotus
#

Hmm at the moment I'm trying to create a place where a user can login then get redirected to place where they can choose the courses they want to take. For example username: Adam
password: hello123
courseOptions: English, Maths, Science
email: hello@hello.com

glacial quartz
#

hmm , should i use Server side session with flask or what to prevent auth spam, like 3 trys chill 20min

#

that or myeb to do it form DB

glacial quartz
#

hmm i could do it form DB but that whay somone can spam my DB and i dont want that, so i need to set this flask but using ServerSideSession Flask-Session , right? i just tryed that but it alwies crys
"RuntimeError: The session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret."
even i added app.secret_key = 'some secret key'

#

using clinet side session in cookie worked np, but i want serverside

#

anyone?

rich panther
#

Anyone use flask? When I change code it doesnโ€™t update unless I reboot

eternal marsh
#

app.run(debug=True)

rich panther
#

I have that set to true in both the main file and wsgi

warm dust
#

i have a .ini file that runs a flask website that streams videofile via opencv. It runs perfectly when I use uwsgi app.ini. Then I deploy it in my emperor.uwsgi.service. The static websites are fine, but when I go to the streaming page, All the text/headers are in position, but the "video" won't stream/show. The page is saying waiting for 192.168.1.38.... What settings should I add to my emperor so that it will also auto refresh the page, because the streaming part of flask is just a Response that changes the image every second.

brave mantle
#

I'm kind of wondering why you're using emperor

#

when uwsgi will do workers for you

#

unless you're going with like a big distributed webapp

#

The best hint to this may actually be in your browser's console

warm dust
#

Its actually not a big problem, I just want to use it in systemd enable emperor.uwsgi.service so that uwsgi will autoplay everytime I turn on my Pi. Is harakiri not related to my problem?

brave mantle
#

I've actually not used emperor, that's why I ask

#

if you put your uwsgi config in uh.. I think it's /etc/uwsgi/

#

I think you can use the uwsgi systemd service

#

eg if your config is named app then you just enable uwsgi@app.service

#

but either way, emperor should work fine, assuming it and its vassals are all configured correctly

#

as well as nginx or whatever webserver you're proxying with

kind steppe
#

!tempmute @abstract orbit 6h spreading chain mail in an on topic category

lavish prismBOT
#

:incoming_envelope: :ok_hand: muted @abstract orbit until Sun, 17 Feb 2019 07:02:45 GMT (spreading chain mail in an on topic category).

floral fulcrum
#

can anyone recommend flask or django or something else?

#

I just want to make a moderately simple site for showing some sports statistics like outputting MySQL to tables in webpages

twilit ivy
#

I need to make a choice for some "quick and dirty" prototyping I just wanted to see what the general coconscious is on bottle vs flask. I have not really worked extensively with either. When I say prototyping I mean there doesn't need to be auth or anything as it is all going to run local and is for demonstration purposes only

brave mantle
#

Bottle vs Flask: They both have a very similar API. Bottle's only advantage is that it's a single file that you can include alongside your app, whereas flask really needs to be installed with pip.

#

If you don't care about that, use flask.

twilit ivy
#

๐Ÿ˜„ :

limpid sandal
#

Can anybody here guide me how to package my flask app as an single file executable on mac

meager anchor
#

single file executable of a flask app? what's the grand goal of this?

steel tiger
#

run the app.py file you made? put it in a docker container and run that?

fossil lotus
#

Just wondering does {% block body %} {% endblock %} specify <body> </body>?

candid basalt
#

Depends on your templates.

#

But generally no, it's just a block with the body name. It does not magically add any tags for you.

fossil lotus
#

Ah ok

outer marsh
#

Looking for some guidance to start hunting down a root cause. I can access a WSGI application when i launch gunicorn via SSH, and open a test port (8000). And i can access the nginx server that is running and listening on port 80. So i know both the Gunicorn and nginx are functioning correctly... But they are not functioning together. When i configure a new service to bind the nginx and gunicorn to the sock file it Doesnt create it/gunicorn cannot access it. The folder that should have the sockfile
/var/run/
has +775 using www-data : www-data. Running ubuntu 18.04. Any suggestions on things to check would be fantastic.

native tide
#

Gone trough the BlueOcean guide for it for debugging?

#

*DigitalOcean

coral ridge
#
[
{'a': 1}, 
{'b':2}, 
{'c':3}
...
]

How would I get an array of ['a','b','c' etc..] from this with JS?

signal jetty
#

I posted sth, but haven't read to the end the thing about JS

coral ridge
#

Figured it out. array.map(d => Object.keys(d)[0])

fossil lotus
#

What's a way to validate emails other than using regex? I've tried validate_email but it doesn't for all emails.

polar wasp
#

validating email is overrated

#

just send an email

#

the mailer won't accept it if it's invalid

#

(what problems are you running into with validate_email)

fossil lotus
#

I've got a school email that ends with .org.uk and it returns None. Got me thinking what other emails would not be valid

#

And sending an email kinda like saying hey click this to validate your account ?

opal leaf
#

yep

#

its the only real way to be sure. you can check for an @ symbol if you really want but trying to regex that its valid or anything is just a waste of time and will annoy people with a weird email address

#

if they dont click it after a certain amount of time just delete their account

polar wasp
#

...honestly i looked at the code to validate_email and it looks pretty rigorous

opal leaf
#

well i think most of the issue is trying to use regex specifically, but again it doesnt really matter since what you really want to know is if that email can be used to contact and identify that specific user

polar wasp
#
>>> validate_email.validate_email('foo+bar@example.org.uk')
True```
#

also what do you mean it returns None? validate_email returns True or False, not None

opal leaf
#

looks like validate email can check if the email servers dns entries exist which is pretty cool

polar wasp
#

@fossil lotus

opal leaf
#

or if the mail server is actually there AND it accepts the email, thats interesting

#

so it does have an alternative to actually sending the email. but it wouldnt surprise me if its basically 99% of sending an email

#

of course without sending it and making the user click it you dont really know whos email address it is still

fossil lotus
#

Ahh sorry didn't clarify

polar wasp
#

for most purposes you'd use an email for you'd want to confirm that the user who typed it in actually owns the address, which is where sending an email comes in

opal leaf
#

yeah imo there is no reason to even take the users email if you dont intend to send something to it

#

just use a username instead

fossil lotus
#

try validate_email.validate_email('foo+bar@example.org.uk',verify=True) You will need Py3dns

#

and I'm using emails in case they forgot their password

polar wasp
#

er

#

you put the quote in the wrong place

floral fulcrum
#

If they need a password you want an email

fossil lotus
#

Sry didn't see that

polar wasp
#
validate_email.validate_email('foo+bar@example.org.uk',verify=True)```
opal leaf
#

makes sense, but i would still send them an email to make sure it works

#

validate_email gets you most of the way though

fossil lotus
#

Yeah that's true I guess I can say if you entered a wrong email an admin account can reset / change it ?

opal leaf
#

hmm if its their login name too

#

then i would just delete the account tbh and let them recreate it, since odds are they wont be able to remember the login if they typo the email

#

you might have an initial login just via cookies that they can use to try to save the account

fossil lotus
#

Oh no they login with a username

opal leaf
#

eg like your email hasnt been verified so please fix that in a big red box at the top of pages

#

ah

#

yeah then just ask them to verify/fix the email

fossil lotus
#

yup yup.

#

ty ty ๐Ÿ˜ƒ

polar wasp
#

@fossil lotus turn debug on

fossil lotus
#

debug on where?

polar wasp
#
>>> logging.basicConfig()
>>> validate_email.validate_email('foo+bar@example.org.uk',verify=True, debug=True)
#

i get DEBUG:validate_email:ServerError or socket.error exception raised (timed out).

#

maybe py3dns is broken?

fossil lotus
#

hmm I think I'll just make it to admin can manually reset the email account.

polar wasp
#

oh wait duh

#

you can still turn verify off and use it to validate the syntax of emails, i'm thinking the check_mx/verify stuff maybe isn't very good

fossil lotus
#

Yeah I wanted to verify the emails initially but moving away from that and just verifying syntax

opal leaf
#

@fossil lotus a general question for you, what will you do to verify that the user is the right person?
eg lets say i am a bad guy and see that a new user was created, so you prob have not yet sent them an email.
what stops me from asking the admin to reset my password and claiming i typoed the email address?

#

its a consideration if its a big / serious site

#

but not a big deal on a private site where you dont expect a lot of traffic

fossil lotus
#

Ughh it's for a school project so don't need to worry about that

opal leaf
#

haha

#

yeah im not sure how you would solve this problem easily if you want to skip verifying the email

#

which makes sense for your school project

fossil lotus
#

Well being honest all I had to do was make a website that showcases what computing and IT courses my school offers but wanted to add some functionality to the website which will help the teachers during an open day.

opal leaf
#

but in general, i guess you would have to ask them for something only the account owner would know.

#

like on steam they can ask what games you had i guess

fossil lotus
#

Rn I'm thinking the student will sit at a computer during the open day make an account with the help of a teacher and do what they want.

#

Yeah I guess so could get a timestamp i.e when a student signs in for the open day and get them to store it or something like that.

hollow flower
#
[2019-02-18 23:46:30,340] ERROR in app: Exception on /api_users/registration [POST]
Traceback (most recent call last):
  File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask/app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask_restplus/api.py", line 329, in wrapper
    return self.make_response(data, code, headers=headers)
  File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask_restplus/api.py", line 350, in make_response
    resp = self.representations[mediatype](data, *args, **kwargs)
  File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask_restplus/representations.py", line 25, in output_json
    dumped = dumps(data, **settings) + "\n"
  File "/usr/lib/python3.7/json/__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "/usr/lib/python3.7/json/encoder.py", line 201, in encode
    chunks = list(chunks)
  File "/usr/lib/python3.7/json/encoder.py", line 438, in _iterencode
    o = _default(o)
  File "/usr/lib/python3.7/json/encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type MethodViewType is not JSON serializable

api_users_service.py: https://pastebin.com/yqB3FSSG
api_users_controller.py: https://pastebin.com/0Ls7CEYN

Umm, ideas?

opal leaf
#

the error message seems to indicate that you passed an object of type MethodViewType someplace you were not supposed to in the function ApiUserRegistration.post

#

also both pastebins have the same code in them

#

its possible the way you are mapping apiuserregistration to your view is wrong but i cant see any other code

hollow flower
#

oof I see. I actually did find the error. I was using a class when I was ment to be defining a function rather.

fossil lotus
#

I know I've been asking a lot of questions lately but bear with me. How do I make it so that an admin can type a username click submit button and it comes up with the necessary sqlite db information under the button.
Also is it possible without passing username like this /foo?username=bar ?

fossil lotus
#

Nvm managed to do it ^^.

hollow flower
#
flask_jwt_extended.exceptions.NoAuthorizationError: Missing Authorization Header

What would be the best way to catch that error?

kindred cosmos
#

Does anyone here know any good resources for django?

hollow flower
#
drifting kettle
#

Any recommended free resources for people just starting out?

#

I've googled quite a few, just wondering what people recommend.