#web-development

2 messages · Page 21 of 1

devout nebula
#

yeah right now I'm learning HTML.

#

all this stuff is new to me so I'm excited; just wanted some insight other than what I read on google.

fathom prism
#

Yea think of JavaScript of adding dynamic content to your website like animations (although css can do some too nowadays) or making a webpage that doesn’t have to “refresh” to get new data. Python fits in as the backend or server to serve your website it’s content and JavaScript will do things to that content.

devout nebula
#

I see, thanks for the clarification... Python is the engine in the car.. but JS is the steering wheel and the Radio.

#

while CSS is the appearance? lol

fathom prism
#

Not great when it comes to analogies but yea that works haha

modern raptor
#

I have a quick question
When I do py manage.py shell I can't type anything after
Why is this?

floral fulcrum
#

is it working?

#

might need to verify python and django is installed and working.

#

maybe make sure you are using the python with the django installed to run it

#
python -m pip list```
modern raptor
#

I just restarted it and it worked

#

Thanks anyways

hollow flower
#

Hey, how would I get this working with namespaces?

    # Provide a way for a user to revoke/unrevoke their tokens
    @app.route('/auth/token/<token_id>', methods=['PUT'])
    @jwt_required
    def modify_token(token_id):
        # Get and verify the desired revoked status from the body
        json_data = request.get_json(silent=True)
        if not json_data:
            return jsonify({"msg": "Missing 'revoke' in body"}), 400
        revoke = json_data.get('revoke', None)
        if revoke is None:
            return jsonify({"msg": "Missing 'revoke' in body"}), 400
        if not isinstance(revoke, bool):
            return jsonify({"msg": "'revoke' must be a boolean"}), 400

        # Revoke or unrevoke the token based on what was passed to this function
        user_identity = get_jwt_identity()
        try:
            if revoke:
                revoke_token(token_id, user_identity)
                return jsonify({'msg': 'Token revoked'}), 200
            else:
                unrevoke_token(token_id, user_identity)
                return jsonify({'msg': 'Token unrevoked'}), 200
        except TokenNotFound:
            return jsonify({'msg': 'The specified token was not found'}), 404
#

I'm having trouble figuring out how I would make that to a class and get the <token_id> from the url part to be passed to a function?

#

I think I got that one already, but ideas on this error?

TypeError: token_in_blacklist_loader() missing 1 required positional argument: 'callback'

Code itself:

# Define our callback function to check if a token has been revoked or not
@jwt.token_in_blacklist_loader
def check_if_token_revoked(decoded_token):
    return is_token_revoked(decoded_token)

is_token_revoked:

def is_token_revoked(decoded_token):
    """
    Checks if the given token is revoked or not. Because we are adding all the
    tokens that we create into this database, if the token is not present
    in the database we are going to consider it revoked, as we don't know where
    it was created.
    """
    jti = decoded_token['jti']
    try:
        token = TokenBlacklist.query.filter_by(jti=jti).one()
        return token.revoked
    except NoResultFound:
        return True
hollow flower
#

Okey, fixed it.

#

What's wrong with this?

Traceback (most recent call last):
  File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "/home/sm/PycharmProjects/REST-API/app/__init__.py", line 32, in <module>
    api.add_namespace(auth_ns)
  File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask_restplus/api.py", line 425, in add_namespace
    self.register_resource(ns, resource, *self.ns_urls(ns, urls), **kwargs)
  File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask_restplus/api.py", line 264, in register_resource
    self._register_view(self.app, resource, namespace, *urls, **kwargs)
  File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask_restplus/api.py", line 287, in _register_view
    resource_func = self.output(resource.as_view(endpoint, self, *resource_class_args,
AttributeError: 'function' object has no attribute 'as_view'
fathom prism
#

Looks like you’re trying to call a function of a function which has no as_view method

dawn ember
#

Hey I just had a quick question in regards to Flask and a just basic counter function that counts the amount of times it has been run but when the website has a lot of traffic the counter jumps all over the place

#

def counter():
counter.counter += 1
counter.counter = 0

#

Sorry I’m on mobile haha

fathom prism
#

Could you clarify what you mean by all over the place? Is it not sequential?

dawn ember
#

Yeah it’s not sequential

#

Obviously when a lot of traffic on the site the console spams quite a lot but yeah the numbers were for sure not sequential

fathom prism
#

How is your website hosted? Is it on nginx or Apache?

#

Or app*

#

And how is the counter variable being stored? Database? Browser memory?

#

Cache?

hollow flower
#

I don't know what is wrong with this so it gives an AttributeError.

auth_controller:

from flask import request, jsonify
from flask_restplus import Resource
from flask_jwt_extended import jwt_refresh_token_required, jwt_required
from app.main.service.auth_helper import Auth
from ..util.dto import AuthDto

api = AuthDto.api
user_auth = AuthDto.user_auth

# TODO: Fix the AttributeError.

@api.route('/login')
class UserLogin(Resource):
    """
        User Login Resource
    """
    @api.doc('user login')
    @api.expect(user_auth, validate=True)
    def post(self):
        # get the post data
        post_data = request.json
        return Auth.login_user(data=post_data)


@api.route('/refresh')
@jwt_refresh_token_required
class RefreshToken(Resource):
    @jwt_required
    def post(self):
        return Auth.refresh_token()


@api.route('/token')
class GetTokens(Resource):
    @jwt_required
    def get(self):
        return Auth.get_tokens()


@api.route('/token/<token_id>')
@api.param('token_id', 'The token identifier')
class ModifyToken(Resource):
    def put(self, token_id):
        return Auth.modify_token(token_id)
hollow flower
#

Could someone give me pointers?

fathom prism
#

in particular, how to set up views

hollow flower
#

I have no views, yet other ones work fine.

fathom prism
#

Sure, but it's probably opinionated and requires a setup you're probably missing somewhere

#

Which endpoint is it thats failing?

#

I could only guess that what you're returning is not valid (e.g. the Auth.<functions>)

hollow flower
#

The failing end-points code is the one pasted above.

marsh canyon
#

hey guys,im having a lil issue with image loading in django

#
    title = models.CharField(max_length = 64)

    image = models.ImageField(
        blank=True,
        upload_to = 'post_images'
        )

    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    posted_by = models.ForeignKey(User, on_delete=models.CASCADE)```
#

my model

#

i made the Post through the admin portal and did put in an image,but when i want to display the Post ,the image dosent appear and when i open it in a new page,it throws a 404

#

but i do have the image inmedia/post_images/

#

any idea what im missing?

#

nvm i fixed it

#

a lil typing mistake in the url pattern

uneven jasper
#

I need some help with a simple Flask error. I'm using CGI and Flask. This is main.html.

#

`<html>
<h1>Form Input test</h1>
<form name="search" action="/cgi-bin/main.py" method="get">
Search: <input type="text" name="searchbox">

<input type="submit" value="Submit">
</form>
in your test.py

</html>
`

#

`from flask import *
#in the form action form action="", put the location of your cgi script and the value of the textbox will be passed to the cgi script. eg.
import cgi

app = Flask('name')

@app.route('/')
def home():
return render_template('main.html')

form = cgi.FieldStorage()
searchterm = form.getvalue('searchbox')
print(searchterm)

if name == "main":
app.debug = True
app.run()
`

#

I'm getting a 500 error.

#

Is there anything wrong?

lofty reef
#

show me your request

patent cobalt
#

@uneven jasper Please don't advertise your question in other channels.

uneven jasper
#

Sorry

lofty reef
#

wouldnt that be running on some port that isnt port 80?

uneven jasper
#

Im runnin offlocalhost

lofty reef
#

thats the error you got?

uneven jasper
#

Yes

#

I have debug on true

lofty reef
#

but you havent imported jinja im confused

kindred cosmos
#

You just need render_template for jinja

uneven jasper
#

I don't know why it'd give me that if I didn't have jinja

#

I imported jinja and now it's saying the page refused to connect

kindred cosmos
#

You need to make sure your template files are in the right place

uneven jasper
kindred cosmos
#

Make a folder called templates

uneven jasper
#

Oh

#

Ok that seems right

kindred cosmos
#

And put main.html in there

uneven jasper
#

Ok, thank you

#

Now it works, thank you!

kindred cosmos
#

No problem. Did it work?

#

Sweet

hollow flower
#

I have problem, which is kind of odd.

Traceback:

[2019-03-09 17:50:44,105] ERROR in app: Exception on /auth/login [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 325, in wrapper
    resp = resource(*args, **kwargs)
  File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask/views.py", line 88, in view
    return self.dispatch_request(*args, **kwargs)
  File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask_restplus/resource.py", line 44, in dispatch_request
    resp = meth(*args, **kwargs)
  File "/home/sm/PycharmProjects/REST-API/app/main/controller/auth_controller.py", line 22, in post
    return Auth.login_user(data=post_data)
  File "/home/sm/PycharmProjects/REST-API/app/main/service/auth_helper.py", line 46, in login_user
    access_token = create_access_token(identity=data['username'], fresh=True)
  File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask_jwt_extended/utils.py", line 141, in create_access_token
    return jwt_manager._create_access_token(identity, fresh, expires_delta, user_claims)
  File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask_jwt_extended/jwt_manager.py", line 476, in _create_access_token
    json_encoder=config.json_encoder
  File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask_jwt_extended/tokens.py", line 67, in encode_access_token
    'type': 'access',
TypeError: unhashable type: 'list'
prime ridge
#

Not strictly Python-related (possibly strictly unpython related) but any advice for learning how to learn enough javascript to make better Flask/Django apps? Are there any tools that provide shortcuts either in the Python language (or jinja2/django templating), or in the PyCharm IDE?

#

@hollow flower Any more context? This looks familiar

#

what are you trying to do exactly?

hollow flower
#

Create access_tokens with flask-jwt-extended, and use username as identity.

kindred cosmos
#

Can you show us the source?

hollow flower
#
@staticmethod
    def login_user(data):
        user = None
        try:
            # fetch the user data
            user = User.query.filter_by(username=data.get('username')).first()
        except Exception as e:
            print(e)
            response_object = {
                'status': 'failed',
                'message': 'Something odd happened.'
            }
            return response_object, 400

        if user is None:
            try:
                user = User.query.filter_by(email=data.get('username')).first()
            except Exception as e:
                print(e)
                response_object = {
                    'status': 'failed',
                    'message': 'User is not known'
                }
                return response_object, 401

        if user and user.check_password(data.get('password')):
            test_data = json.dumps(data)
            print(test_data)
            access_token = create_access_token(identity=data['username'], fresh=True)
            refresh_token = create_refresh_token(identity=data['username'], expires_delta=timedelta(hours=1))
            response_object = {
                'status': 'success',
                'message': 'Successfully logged in.',
                'authorization': {
                    'access-token': access_token,
                    'refresh-token': refresh_token
                }
            }
            return response_object, 200
#

This is the source for it.

#

It's the login_user from auth_helper.

prime ridge
#

Hmmm

kindred cosmos
#

What's the name of file that function/method is in?

prime ridge
#

access_token = create_access_token(identity=data['username'], fresh=True)
So this is the line in that code where it starts to trip up, if I'm reading that traceback correctly. I'm trying to figure out what list it's talking about

#

What is data['username']

#

Is that just a string?

#
>>> {list(): "Lists aren't hashable, dork!"}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>>```

Are you passing a list anywhere it's either getting used as a dictionary key, or between processes (e.g. to a worker) or anything?
hollow flower
#

data['username'] is basically a string, from json request.

prime ridge
#

basically a string, 🤔

#

I noticed before you did

#

username=data.get('username')).first()

#

Which suggests to me that data['username'] isn't a string.

#

@hollow flower

#

If it's a list, it would explain why that line of code is giving you the unhashable type error.

hollow flower
#

Oof, that's probably my problem.

heady basin
#

i installed xdebug to profile stuff with php, it turned on some stack trace shit that only puts the first useless line into error.log instead of the good old error messages

#

i disabled everything to do with it in php.ini and restarted webserver but it still does it

#

how do i get rid of this shit forsenY

hollow flower
#

@prime ridge It's a dict apperently.

'dict' object is not callable
prime ridge
#

Oh right, well that makes sense

#

hm

#

oh I misread something above too

#

Bah!

hollow flower
#

Huh?

kindred cosmos
#

@heady basin This is a python server...

#

But you probably didn't edit the correct php.ini file

uneven jasper
#

I want to print the entered data from this html page into the terminal. I'm using flask and cgi. My html

#

`<html>
<h1>Form Input test</h1>
<form name="search" action="/cgi-bin/main.py" method="get">
Search: <input type="text" name="searchbox">

<input type="submit" value="Submit">
</form>

</html>**This is main.py**
from flask import *
#in the form action form action="", put the location of your cgi script and the value of the textbox will be passed to the cgi script. eg.
import cgi

app = Flask('name')

@app.route('/')
def home():
return render_template('main.html')

form = cgi.FieldStorage()
searchterm = form.getvalue('searchbox')
print(searchterm)

if name == "main":
app.debug = True
app.run() `

kindred cosmos
#

Please use the ` for send code

uneven jasper
#

Sorry about that, It's impossible to add paragraphs.

kindred cosmos
#

Shift + Enter

uneven jasper
#

Ok thanks

kindred cosmos
#

No

Problem :)

uneven jasper
#

My mouse scrolls like 15 lines too. lol

#

There we go

kindred cosmos
#

I am pretty sure app = Flask('__name__') is supposed to be app = Flask(__name__)

uneven jasper
#

Ok, thanks.

#

Still not printing

#

It's taking me to a 404 page when I enter data.

kindred cosmos
#

Please send me a screen shot of your code

uneven jasper
#

Ok

kindred cosmos
#

You need to make another endpoint

uneven jasper
#

?

kindred cosmos
#

Which would require you to make another function

#
@app.route('/search')
def search(request):
    form = cgi.FieldStorage()
    searchterm =  form.getvalue('searchbox')
    print(searchterm)
#

Whoops...

#

I forgot it's three back ticks

uneven jasper
#

What i'm trying to do is make randomly generated forms for people to take and then the data get's sent to me via email.

#

Should have I used the search input type?

kindred cosmos
#

Are you talking about your html?

uneven jasper
#

Yes

kindred cosmos
#

You're html is fine

#

Your code is not

#

You need to make another endpoint/route for where your search form will submit to

#

Vc?

uneven jasper
#

I dont know.

#

I'm trying to print it to make sure I can store the input in a variable.

#

Once I get it in a variable I can use it accordingly

kindred cosmos
#

I understand that

#

But you still have to create a new route to do that

#

Right now there's issues in your code that need to be fixed for that to happen

uneven jasper
#

Oh, so the form and searchterm should be in a route so they can loop?

kindred cosmos
#

What loop

uneven jasper
#

So they can be executed more than once?

kindred cosmos
#

Yeah you don't need a loop to do that

uneven jasper
#

Ok

#

I just put in the extra route

kindred cosmos
#

Okay now you need to make sure that your html form action attribute is set to that route

uneven jasper
#

Ok

#

Alright, I got this: builtins.TypeError
TypeError: search() missing 1 required positional argument: 'request'

kindred cosmos
#

I need to see the code

uneven jasper
#

Ok

kindred cosmos
#

Can you give me the full stack trace as well?

#

Nvm

#

Get rid of the request in def search(request):

uneven jasper
#

Done

kindred cosmos
#

Does it work now?

uneven jasper
#

Indentation error on form variable. I removed the indent and It gave me a syntax error.

kindred cosmos
#

You need to make sure you either using all spaces or all tabs

uneven jasper
#

I'm using tabs

kindred cosmos
#

Make sure everything is tabs then

uneven jasper
#

I removed indentation from everything and re indented. Still got an error.

kindred cosmos
#

Copy and paste your code in to chat

uneven jasper
#

`
from flask import *
#in the form action form action="", put the location of your cgi script and the value of the textbox will be passed to the cgi script. eg.
import cgi
import jinja2

app = Flask(name)

@app.route('/')
def home():
return render_template('main.html')

@app.route('/search')
form = cgi.FieldStorage()
searchterm = form.getvalue('searchbox')
print(searchterm)

if name == "main":
app.debug = True
app.run()
`

#

Im getting an error at line 13. At the form variable.

kindred cosmos
#

You need to have def search(): in there

#

Between @app.route('/search') and form = cgi.FieldStorage()

#

I said to remove request not the whole line haha

uneven jasper
#

Oh! lol ok

#

builtins.TypeError TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.

kindred cosmos
#

Add return render_template('main.html') at the bottom of the function

#

the search function

uneven jasper
#

(I typed in none)

#

Thank you for your help!!!

kindred cosmos
#

See if you type something if it still works

uneven jasper
#

Okay

#

So I typed in "None" the first time. Apparently it means something because even when I reset it, it prints 'none'.

kindred cosmos
#

Yeah so you are using some cgi library when your application is running in flask

#

It's fundamental how cgi and flask work

uneven jasper
#

?

kindred cosmos
#

Get rid of the line form = cgi.FieldStorage()

uneven jasper
#

I was wondering what that did

#

It seemed useless

kindred cosmos
#

then change searchterm = form.getvalue('searchbox') to searchterm = request.form['searchbox']

#

Yeah cgi is just a completely different technology then what flask uses

uneven jasper
#

Oh ok.

#

That explains a lot. lol.

kindred cosmos
#

Cgi works on file basis while flask is wsgi application

uneven jasper
#

werkzeug.exceptions.BadRequestKeyError
werkzeug.exceptions.HTTPException.wrap.<locals>.newcls: 400 Bad Request: KeyError: 'searchbox'

#

That's a weird error.

kindred cosmos
#

Did you submit to the form?

uneven jasper
#

Yes

#

Is something wrong with searchterm = request.form['searchbox'] ?

kindred cosmos
#

Yeah

uneven jasper
#

It matches the name though.

kindred cosmos
#

jk you should of switch it too request.args.get('searchbox')

#

request.form is if your submitting a post request

#

But you are doing a get request

uneven jasper
#

Okay

#

Oh my gosh, it works!

#

Even after I enter something, it still works!

kindred cosmos
#

Nice

uneven jasper
#

Thank you for your help!!

kindred cosmos
#

No problem my dude

uneven jasper
#

Gosh time flies when your fixing... stuff.

prime ridge
#

If left unspecified, do users submitting requests to a Flask application have any say over what type Python interprets a parameter as?

#

Here's my example.

#
    b = request.args.get('b', 0)  # Note I did not specify type=int, so the server may assume str```
#

These should both be type=int for the calculator to function

#

It seems that, when used normally, the type will default to str

#

but I'm wondering if the user (e.g. a malicious one) could somehow make the server parse it as a list, or some other type

fathom prism
#

@prime ridge , the rule is to never trust the user input

prime ridge
#

Of course that's the rule

fathom prism
#

They could possibly take advantage of Python's duck type and could possibly perform malicious acts that will break your application

prime ridge
#

Yeah, that's exactly what I'm getting at. But is it ACTUALLY possible, is the question

#

I wouldn't write sites that way

fathom prism
#

Anything is possible

#

If you don't safe guard against it

prime ridge
#

If Flask handles it then it isn't possible.

#

e.g. if flask always defaults to a string

fathom prism
#

Ok, sure. Why don't you write some tests then to confirm if thats true?

prime ridge
#

I don't know how

fathom prism
#

It shouldn't be too hard to write some unit tests

#

look into pytest

prime ridge
#

I know how to write unit tests

#

I don't know how I'd forge a GET/POST request that tricks Python into typing something other than a str

#

The question to begin with is whether that's possible.

fathom prism
#

Use postman or curl

#

I don't know enough of the internals, but its better to test or read the source code itself

prime ridge
#

I did, but I stopped when I didn't know how to specify type in a request. I'd imagine there might be a header for that.

#

I know you can specify content type, but idk if that's just for any field

#

I think that's more for, like, whether you're sending json/xml/etc

#

Flask has an option to get a list from a request, but you have to explicitly use that function and it'll check for duplicate parameters

#

e.g. item=1&item=2 == [1, 2]

fathom prism
#

So I'll give you a simplified example.

Lets say your application is sending JSON which can have different types and your function was expecting a string, but supposedly could also get a number

prime ridge
#

oh hey, good point

#

json has types

fathom prism
#

Flask will not deserialize it to correct the term

#

type*

#

that YOU expect, it will deserialize it whatever was sent

#

its up to the developer to handle the different types of JSON payloads at that point

prime ridge
#

Yeahhh, lemme check and see what happens if I pass a json int when the type is unspecified

fathom prism
prime ridge
#

Looks like by default flask doesn't parse arguments from json. I guess that's a behavior you have to code manually

#

.get_json()

#

okay, so if you DO that though

#
    if request.method == 'POST':
        a = request.get_json()['a']
        b = request.get_json()['b']
        return jsonify(result=a+b)```
#

Sending

{
    "a": "1",
    "b": "2"
}
``` returns `"12"`
#

but sending

#
{
    "a": 1,
    "b": 2
}```
returns `3`
fathom prism
#

Yup.

prime ridge
#

Interesting. I know some really badly coded python sites where, were it possible to specify type on the inputs like this, it would be catastrophic

#

I've read code with really bad input validation that uses iteration to validate input that goes directly into an SQL query where, were you to give it a list, you could bypass that check entirely

fathom prism
#

Thats where they hire you to fix those issues

#

👍

prime ridge
#

Ha, I wish. It is a company I code for, but they're too stubborn to replace this awful legacy code.

#

Some day...

hollow flower
still gazelle
#

Ok

#

this might seem like a crazy request idk

#

but im trying to run flask and discord in the same application

#

this is what i have so far

#
from flask import Flask, jsonify, request
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
app = Flask(__name__)

#Discord Bot Loads
Bot = discord.Client()
bot = commands.Bot(command_prefix='--')
bot.remove_command('help')

#Waits for PUT Request
@app.route('/questionData', methods=["PUT"])
def newQuestion():
    data = request.get_json()
    #Post discord embed
    return jsonify(data), 201

if __name__ == '__main__':
    app.run(debug=True)
#

i tried to add on_ready() and bot.run() but the site refused to load

#

i want to make it so that when it receives a PUT request, it uses that data in the discord embed

hollow flower
#

I don't think you can do that..

#

Does it output any errors?

still gazelle
#

@hollow flower the webpage wont load

hollow flower
#

How are you calling it?

still gazelle
#

@hollow flower one sec

#

@hollow flower ```py
from flask import Flask, jsonify, request
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
app = Flask(name)

#Discord Bot Loads
Bot = discord.Client()
bot = commands.Bot(command_prefix='--')
bot.remove_command('help')
@bot.event
async def on_ready():
await bot.say("Ready")

#Waits for PUT Request
@app.route('/questionData', methods=["PUT"])
def newQuestion():
data = request.get_json()
return jsonify(data["answers"]), 201

if name == 'main':
app.run(debug=True)
bot.run("")

hollow flower
#

Last time I checked, you probably can't mix async code with non-async.

still gazelle
#

ok

#

do you suggest anything?

hollow flower
#

Does the bot log-onto Discord though?

still gazelle
#

last line does

#

just didnt put token

hollow flower
#

Just checking, hmm.

#

I don''t see how that's supposed to work.

still gazelle
#

hmmm

#
#Waits for PUT Request
@app.route('/questionData', methods=["PUT"])
def newQuestion():
    data = request.get_json()
    #Discord Embed goes here.
    return jsonify(data["answers"]), 201
hollow flower
#

So what's your goal exactly?

still gazelle
#

to send a message in discord using the data included in the PUT

#

and for it to send the message right after the PUT

hollow flower
#

Then your code is wrong. You can return the 201, but you don't need to the data itserlf.

#

Code the discord embed part.

still gazelle
#

yes i understand that

#

but how would i send the message if the bot isnt loaded?

hollow flower
#

Just try and see.

still gazelle
#

why would it work?

#

it wouldnt be connected to any discord user/bot

hollow flower
#

And is that bot.run() inside the if __name__ == '__main__': identet correctly?

still gazelle
#

No.

hollow flower
#

Ident it.

still gazelle
#

does it need to be there?

#

ok

hollow flower
#

And try it.

still gazelle
#

think it worked?

#

ill try to send a message to a channel

#

didnt work

hollow flower
#

The bot is connected though?

still gazelle
#

im going to run it through putty to see if it connects

hollow flower
#

Also,

@bot.event
async def on_ready():
    print("Ready")
#

It outputs to console.

still gazelle
#

does it need to do anything on ready?

hollow flower
#

No, but I have this.

@bot.event
    async def on_ready():
        bot.uptime = datetime.datetime.utcnow()
        # Create database connection
        #bot.pool = await asyncpg.create_pool(config.postgresql, min_size=3, max_size=5)
        await bot.change_presence(status=discord.Status.online, activity=game2)
        print(f'\n\nLogged in as: {bot.user.name} - {bot.user.id}\nVersion: {discord.__version__}\n')
still gazelle
#

this is the error im getting on putty

#

$ python app.py
  File "app.py", line 20
    await bot.send_message(discord.Object(id='538511258375159850'), 'hello')
            ^
SyntaxError: invalid syntax
#

i dont think this'll work

hollow flower
#

You're doing it incorrectly. That's not a the proper way to send a message.

still gazelle
#

what do you mean?

hollow flower
#

Are you on rewrite branch?

still gazelle
#

no

hollow flower
#

FUck

still gazelle
#

what

hollow flower
#

Still its incorrect

#

And you should be on rewrite

fluid horizon
#

where is this send_message from?

hollow flower
#

Why use discord.py v1.0 (rewrite)?
Reference the tags in the brackets for details on specific points.
• Improved documentation
• Context always passed for bot commands
• New ctx shortcuts
• Robust websocket reconnect logic
• Model-based OOP
• Ability for sub-commands to not invoke parent
• Async checks and events
• Case insensitive command name support
• NSFW channel check support
• Channel category support
• Animated emoji support
• Audit log support
• Webhook support
• Improved activity support
• Memory and performance improvements
• New raw events and functions
• Bot and Cog Template creator

Why not?
Rewrite is stable, but still in active development. It is discouraged to use if:
• You won't keep your library up to date
• You won't keep your code up to date with any breaking changes
• You won't subscribe to news of breaking changes with ?rewrite
• You don't want to rewrite your existing code to be compatible

still gazelle
#

ok

#

ill use it for a future project

#

luna, im trying to get discord.py and flask to run on the same app

hollow flower
#

Example of correct way of sending a message.

await client.send_message(message.channel, 'Hello')
fluid horizon
#

may i ask why?

still gazelle
#

so that on PUT it uses the data to send a message in discord

fluid horizon
#

@hollow flower you can use send_message on discord.Object, not really advised, but it's valid

hollow flower
#

Did not know that.

#

Been using rewrite too much. :D

polar wasp
#

wait, i thought there was some reason you couldn't

fluid horizon
#

it's in async faq, it grabs the id from it iirc

still gazelle
#

its been working for me

fluid horizon
#

you can't do this in rewrite though

still gazelle
#

is what am trying to do possible?

fluid horizon
#

it's also not the greatest idea to run both a flask server and a bot in the same process

still gazelle
#

how would I send a message on PUT then

fluid horizon
#

out of curiosity, why a webserver? couldn't you integrate this directly to the bot?

still gazelle
#

others will be performing the PUT

#

again, the data will be put into a message on discord

fluid horizon
#

ah...

still gazelle
#

wish it was as easy as creating a json lol

#

so is what am trying to do not possible?

#

ok

#

so im testing this on putty

#

and as soon as i do control +c, it prints "Ready"

#

so I assume only one can be run at once

coral sorrel
#

Heyo

still gazelle
#

hi

coral sorrel
#

Your issue sounds like you're attempting to run the blocking start calls for both the bot and the flask site at the same time

still gazelle
#

basically, yes

coral sorrel
#

It's best if you separate the site and bot into two different processes instead

still gazelle
#

how would i make a command activate after PUT

coral sorrel
#

Otherwise if you must have it, you need to use non blocking start calls to run them and handle the loop running yourself

#

With flask though you probs should be avoiding the development server environment which is likely what you're using

#

If you only want an API, why not take advantage of aiohttp

#

It's already part of the bots dependency list with dpy

still gazelle
#

ok

#

would it be possible to call the discord create message API manually

coral sorrel
#

Since you have things already it'll make things a little simpler but you'll still need to read up on how to create the API endpoints with the lib.
And sure you could call discord send message API endpoint but that's a bad idea

still gazelle
#

ok

coral sorrel
#

If you want to just emit a message and not interact you should use webhooks

still gazelle
#

hmm

#

that might be a good idea

#

i think im going to try to use webhooks

#

because that would make sense

coral sorrel
#

You don't have to worry as much about ratelimits or the bot API complexity, plus you can still send all the normal stuff: content, embeds, attachments.
Plus you don't have to stress at all about bot accounts or permissions.

#

It's worth using if it's only meant to be message emitting

still gazelle
#

yes

#

only message emitting

coral sorrel
#

Easy choice then :)

#

Especially since you can just send via requests in flask

still gazelle
#

@coral sorrel webhook worked btw

#

attempted to call the discord create message API manually, but didnt work

woeful sphinx
#

hi guys anyone familiar with UWsgi and nginx etc etc

#

right now i am trying to get uwsgi to run as a systemctl service

#

it works if i run uwsgi --ini ini.ini

devout current
steel tiger
#

Why use Flask-RESTful when you can just do the "normal" views way

hollow flower
#

Does anyone have experience with websub in Flask?

Traceback (most recent call last):
  File "/home/sm/PycharmProjects/REST-API/run.py", line 4, in <module>
    app = create_app(os.getenv('BOILERPLATE_ENV') or 'dev')
  File "/home/sm/PycharmProjects/REST-API/app/__init__.py", line 27, in create_app
    from app.main.errors import bp as errors_bp
  File "/home/sm/PycharmProjects/REST-API/app/main/__init__.py", line 15, in <module>
    from app.main import routes
  File "/home/sm/PycharmProjects/REST-API/app/main/routes.py", line 1, in <module>
    from app.main.controllers.websub_controller import hub
  File "/home/sm/PycharmProjects/REST-API/app/main/controllers/websub_controller.py", line 4, in <module>
    from app.main.service.websub_service import hub
  File "/home/sm/PycharmProjects/REST-API/app/main/service/websub_service.py", line 10, in <module>
    hub = Hub(SQLite3HubStorage('server_data.sqlite3'), celery, **config.Config)
TypeError: type object argument after ** must be a mapping, not type
steel tiger
#

config shouldn't return the config class thingy

#

@hollow flower

hollow flower
#

But that's how I have done it though.

steel tiger
#

Then change it to a dict I guess

hollow flower
#

How?

steel tiger
#

¯_(ツ)_/¯

hollow flower
#
Traceback (most recent call last):
  File "/home/sm/PycharmProjects/REST-API/venv/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "/home/sm/PycharmProjects/REST-API/run.py", line 2, in <module>
    from app import create_app, ma, jwt
  File "/home/sm/PycharmProjects/REST-API/app/__init__.py", line 10, in <module>
    from app.main.config import config_by_name
  File "/home/sm/PycharmProjects/REST-API/app/main/__init__.py", line 15, in <module>
    from app.main import routes
  File "/home/sm/PycharmProjects/REST-API/app/main/routes.py", line 1, in <module>
    from app.main.controllers.websub_controller import hub
  File "/home/sm/PycharmProjects/REST-API/app/main/controllers/websub_controller.py", line 4, in <module>
    from app.main.service.websub_service import hub
  File "/home/sm/PycharmProjects/REST-API/app/main/service/websub_service.py", line 10, in <module>
    hub = Hub(SQLite3HubStorage('server_data.sqlite3'), celery, **ConfigDict.__dict__)
TypeError: 'type' object is not subscriptable

Hmm, so close.

fair pumice
#

I guess this question is better in the web development

#

I have image directory I'm working with on a live server by atom the images work when I click on the index.thml but don't work when on the live server

#

the path is standard path to the sub directory where the images are

#

anyone know of why the live server would not display images ?

elder nebula
#

It should

#

@fair pumice Did you tried to get the images with css url()?

#

Because that doesnt work for live server, for obvious reasons. Because then the live server owner could explore your computer.

#

The images must be on the same folder as the index.html

#

Otherwise, it doesnt work

native tide
#

Hey guys. Anyone here know django?

#

I need to create a painel in my website with django + rest

#

i see that django admin default painel have the options to create users and groups

#

and can give acess to each table for each user/group

#

but i friend my told me that's unsafe and can cause vulnerability

#

but i see that's a very easy way to do this.

#

anyone can help me to understand?

elder nebula
#

@native tide It can be unsafe, if you don't know what are you doing. Django is pretty much safe, because the code is hidden. If that project isnt going to public, then you dont need to worry about safety so much. I suggest you to get started with tutorials on youtube. I got started with Corey Schafer's Django blog tutorial, you get the basic idea, how to create login and register system, views, How to delpoy and other stuff what is needed to get started. @native tide

#

The most important thing is to turn off the Debugging when you deploy / launch the web app

#

And Corey Schafer is in this discord server. I think??

#

Got alot of help from Corey's youtube videos

native tide
#

@elder nebula: Actually, i don't understand when he said that it's unsafe. How can Django can be unsafe with the default admin configuration?

#

That's don't make sense to me

#

What django gives me in the default admin configuration it's exactly what i need

#

but he make me scared telling me that's unsafe

#

@elder nebula : What do you mean with "if that project isnt going to public" ?

quiet solstice
#

Not exposed to the internet

native tide
#

The project is for a public institution

#

why i will make a project for not expose for the internet?

elder nebula
#

If its the default admin, then its pretty safe

steel tiger
#

With flask-restful, should I be splitting it up into diffrent files inegrated into my blueprints/components or should I make one large file for all of the API?

#

I would prefare the first one but not sure if is possible by doing it "cleanly"

lost saddle
#

Django already tells you what you should do before deployment for possible security issues

#

python manage.py check --deploy

abstract basin
#

[DJANGO] When I deploy to Heroky, this error occurs

registration/login.html
Request Method:    GET
Request URL:    https://nameless-lake-14525.herokuapp.com/restaurant/sign-in/?next=/restaurant/
Django Version:    2.1.7
Exception Type:    TemplateDoesNotExist
Exception Value:    
registration/login.html
Exception Location:    /app/.heroku/python/lib/python3.7/site-packages/django/template/loader.py in select_template, line 47
Python Executable:    /app/.heroku/python/bin/python
Python Version:    3.7.2
Python Path:    
['/app',
 '/app/.heroku/python/bin',
 '/app',
 '/app/.heroku/python/lib/python37.zip',
 '/app/.heroku/python/lib/python3.7',
 '/app/.heroku/python/lib/python3.7/lib-dynload',
 '/app/.heroku/python/lib/python3.7/site-packages'] ```

But when I run on localhost, I have made changes in django/contrib/auth/views.py
and changes registration/login.html to restaurant/sign_in/html

The page works at localhost:8000/restaurant/sign_in.html but not on heroku at
www.example.com/restaurant/sign_in.html
#

How can I make it work?

#

Requirements.txt

chardet==3.0.4
defusedxml==0.5.0
dj-database-url==0.5.0
Django==2.1.7
django-bootstrap3==11.0.0
django-braces==1.13.0
django-oauth-toolkit==1.2.0
django-rest-framework-social-oauth2==1.1.0
djangorestframework==3.9.2
gunicorn==19.6.0
idna==2.8
oauthlib==3.0.1
Pillow==5.4.1
PyJWT==1.7.1
python-social-auth==0.3.6
python3-openid==3.1.0
pytz==2018.9
requests==2.21.0
requests-oauthlib==1.2.0
six==1.12.0
social-auth-app-django==3.1.0
social-auth-core==3.1.0
stripe==1.37.0
urllib3==1.24.1
whitenoise==3.2.1
psycopg2==2.7.7
psycopg2-binary==2.7.7
lost saddle
#

Did you properly configured template dir inside your settings

abstract basin
#

Yes. The url works fine on Localhost cause I made changes in django/contrib/auth/views.py in site_packages

but as i am trying to deploy to heroku, it shows template error here only

lost saddle
#

Can you show your template settings

abstract basin
#
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.media',
                'social.apps.django_app.context_processors.backends',
                'social.apps.django_app.context_processors.login_redirect',
            ],
        },
    },
]
#
             --> epiktaskerapp
                                --> templates ```
#

code structure is like this

lost saddle
#

Oh

#

I just imagined that you would use the templates folder django-admin created for you

#

That may be your problem and I'm not sure how can your local one work

#

Mind trying to either relocate the templates to the root directory

#

Or simply change the 'templates' to 'templates/epiktaskerapp'

#

Although

#

I think APP_DIRS is for searching inside the apps for the templates

#

hmm

abstract basin
#

Consider me a beginner.
I am trying changing templates
And my localhost worked
cause I changed (django/contrib/auth/views.py in site_packages)

    """
    Display the login form and handle the login action.
    """
    form_class = AuthenticationForm
    authentication_form = None
    redirect_field_name = REDIRECT_FIELD_NAME
    template_name = 'restaurant/sign_in.html'
    redirect_authenticated_user = False
    extra_context = None

template name here from registration/login.html to restaurant/sign_in.html

lost saddle
#

Why did you change that?

#

You should NOT change any library code like that especially if you are a beginner

#

You should instead inherit the class in this case and put your template there

abstract basin
#

I changed because I was following a tutorial with django 1.10 and he has restaurant in url
And I wanted the same in url in django 2.1.7

lost saddle
#

If the tutorial changes library code stop that tutorial immediately

#

Inherit LoginView instead

#

And in the class that you inherit the LoginView change template_name

#

That's it

abstract basin
#

Naa tutorial didnt change library code cause in old version I guess it wasnt necessary?! (maybe)

lost saddle
#

It still isn't necessary

#

I already told you

abstract basin
#

Okay! I will make it as it was on default. I will update you in few minutes

lost saddle
#

Anyone knows anything like whitenoise but for media?

still briar
#

What do you mean?

lost saddle
#

Sorry

#

Whitenoise is a wsgi-library for serving statics with the wsgi application

#

Instead of serving them with another server

#

Nothing? :(

worthy compass
#

i have a very small project that takes information from files and stores it in a .js file for display in a browser

#

it needs to update pretty often

#

what is a good way to structure/run this project?

full lynx
#

Anyone have best practice in dealing with abstract views in Django?

#

for example

#
class NoteAddView(LoginRequiredMixin, SubscriptionRequiredMixin, AjaxMixin, CreateView):
    template_name = 'rental/standard_form.html'
    form_class = NoteForm

    def get_success_url(self):
        return self.request.META.get('HTTP_REFERER', '/')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['page_title'] = 'Add Note'
        return context

class ContactNoteAddView(NoteAddView):
    model = ContactNote

    def form_valid(self, form):
        form.instance.contact = Contact.objects.filter(pk=self.kwargs['pk']).get()
        return supe r().form_valid(form)

#

I'm thinking this is the cleanest way to doing it but im feeling a bit unsure

#

if anyone has any other suggestions

tardy pasture
#

Are you going to be using NoteAddView elsewhere @full lynx ?

full lynx
#

Yes, for each model more or lesss

#

Have like a dozen xNoteAddView(NoteAddView)

#

@tardy pasture

tardy pasture
#

Without looking at things more in-depth, nothing you wrote gives me code-smell feelings.

#

@full lynx

#

maybe that space in supe r

#

but that's really just linting / typos.

full lynx
#

I ended up going with the above syntax yesterday and my subsequent children models look like

#
class LeaseNoteAddView(NoteAddView):
    model = LeaseNote
    form_class = LeaseNoteForm

    def form_valid(self, form):
        form.instance.lease = Lease.objects.filter(pk=self.kwargs['pk']).get()
        return super().form_valid(form)


class LeaseNoteEditView(NoteEditView):
    model = LeaseNote
    form_class = LeaseNoteForm


class LeaseNoteDeleteView(NoteDeleteView):
    model = LeaseNote
#

it looked tidy enough

tardy pasture
#

Do more of the inherited views have things like custom validation?

#

There's a couple of things that I would consider:

#

If it starts to feel boilerplate-y, then there's probably an optimization that you can make with the views. If you have a bunch of views where all you are doing is specifying models or form classes, you might be able to get away with a single view.

#

As a counterpoint, you might be over-optimizing; this is a pretty valid use of abstract views, and it gets the job done.

hollow flower
#
Traceback (most recent call last):
  File "/home/sm/PycharmProjects/messis-restful-api/venv/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "/home/sm/PycharmProjects/messis-restful-api/venv/lib/python3.6/site-packages/flask/cli.py", line 76, in find_best_app
    app = call_factory(script_info, app_factory)
  File "/home/sm/PycharmProjects/messis-restful-api/venv/lib/python3.6/site-packages/flask/cli.py", line 114, in call_factory
    return app_factory(script_info)
  File "/home/sm/PycharmProjects/messis-restful-api/app/api/__init__.py", line 17, in create_app
    app.config.from_object(config_by_name[config_name])
KeyError: <flask.cli.ScriptInfo object at 0x7f8a7758fa20>

What am I doing wrong when trying to execute that with IntelliJ PyCharm, with the run configuration thingy?

lost saddle
#

Is it possible to translate JsonResponse in django

lost saddle
#

with iI8n

native tide
#

Can you run Flask offline?

deep cave
#

sure, it'll happily run off the users localhost.

native tide
#

Ok thanks

vernal kraken
#

Im getting a weird issue where the autofill for Google places API sometimes doesn't work. Im using Flask for my app. Has anyone else had this issue? Usually refreshing the page fixes it, but its really annoying and I don't want users to try it till its 100% working

#

Never had the problem using it before on just pure bootstrap projects until now

uneven jasper
#

I'm getting a 404 error on my flask app. I'm using this line of code to get information from the html.

#

@app.route('/p1') def search(): N = request.args.get('name') #name print(name) N = request.args.get('gender') #gender print(gender) return render_template('name.html', gend=gender) #no extra comment at end.

#

My html:

#

`<html>

<style>
h1 {
font-family: monospace;
color: blue;
}

p {
font-family: monospace;
color: blue;
}

p {
font-family: monospace;
color: blue;
}
</style>

<title>Form input test</title>
<h1>Form Input test</h1>
<form name="/p1" action="/search" method="get">
Name: <input type="text" name="name">

<select name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>

<input type="submit" value="Submit">

</form>

<p>Testing testing, 123.</p>

</html>
`

#

(Im using flask)

#

Okay I'll be back later. Tag me please.

native tide
limber orchid
#

for anyone who's familiar with pythonanywhere web apps... are source files private/secure?

#

I want to make a reddit bot callable on a webpage (it updates user flair for our subreddit and the bot goes down sometimes and they message the mods to complain then)

#

but the config file has login credentials/keys etc

rough jasper
#

django
how can i get just the request headers and not all the other crap i get with requests.META??

vernal kraken
#

@uneven jasper if you are getting form in you gotta add in methods=['GET','POST'] within your route

#

ie @app.route('/p1', methods=['GET','POST'])

native tide
#

How can you run flask on a particular domain?

vernal kraken
#

Wherever you host it you can configure the domain DNS to point to it

#

ie I use Heroku and when you add a custom domain it just gives you a string to point the url to

native tide
#

So I went thru the examples on deploying with heroku but im still confused on how to deploy using a certain url

candid basalt
#

@limber orchid I believe they are. Yet, you'd be better checking this out with their support. They are really nice.

limber orchid
#

yeah I finally heard back from them just now, they said as long as it's not in a static directory or being served to the user somewhere in the code, then it can't be seen

#

thanks!

candid basalt
#

@rough jasper I think you can filter by those with keys starting with HTTP_.

#

@native tide Domain and url are different things. Can you show an example of what are you trying to achieve?

native tide
#

basically what I want is instead of http://127.0.0.1:5000/solve I want it like http://dominus/solve

candid basalt
#

Is that for local usage only?

#

Or do you want it to be available to everyone in the internet?

native tide
#

everyone on my wifi network

candid basalt
#

That might not be easy. In that case you will need some kind of local DNS setup or make everyone adjust their hosts file and add record pointing to your IP address there.

native tide
#

I can get the hosts file edited

candid basalt
#

Everyone who is intended to be able to access the resource will have to do it.

#

Not just you.

native tide
#

Yeah thats fine

#

Its not like a hundred people just like 5 or so

candid basalt
#

In that case it's doable.

#

First you will need a static IP address.

#

I.e. DHCP won't work.

native tide
#

Can it be a vps server I rent?

candid basalt
#

As long as it's reachable via the static IP address - yes, sure.

#

Next xxx.xxx.xxx.xxx dominus line should be added into the hosts file for every client accessing the server, where xxx... is the IP address.

#

Start with yourself and see if it works.

native tide
#

Ok

candid basalt
#

Actually, IP address should be first. I've edited the message.

#

Obviously, you will have to set up your resource on that VPS you mentioned on port 80.

rough jasper
#

@candid basalt but referer doesn't start with HTTP_

native tide
#

Wait why port 80?

#

So basically edit my hosts file to xxx.xxx.xxx.xxx dominus and then start the flask server on that vps using localhost:80

candid basalt
#

http://dominus/solve has no port specified. This means default one is used. Default port for HTTP is 80.

native tide
#

Ahh ok

candid basalt
#

Yes, you pretty much nailed it.

rough jasper
#

no that gives me all the crap i don't want

#

@candid basalt

#

A dictionary containing all available HTTP headers. Available headers depend on the client and server, but here are some examples:

#

the available headers depend on the client and server

#

and i don't care about the servers headers

candid basalt
#

Did you try to filter by HTTP_?

rough jasper
#

REMOTE_ADDR doesn't start with HTTP_

#

but local

#

within django

#

i am probably being stupid but it is kinda late

candid basalt
#

I think REMOTE_ADDR is not a HTTP header.

rough jasper
#

oh shit

candid basalt
#

At least I'm not sure if it has to deal with the protocol itself.

rough jasper
#

you're right

candid basalt
#

In any case if you want a given list of headers - you can just pick those you are interested in and output them.

rough jasper
#

i am stupid

#

i need to filter for HTTP_

#

and the otherones i have to just use the key itself

#

thnx for your help @candid basalt

native tide
#

@candid basalt Hey again. So I set my macs localhost file to xxx.44.xx.238 dominus. I then logged onto the vps with xxx.44.xx.238 as its IP and setup my flask application on it

#

I opened up http://127.0.0.1/solve

#

on my vps and it loaded fine. I then tried to go to

#

http://dominus/solve but all I got was the little loop

#

that signifies that it is loading

#

this has happened for about 10 minutes now. Any reason as to why?

lost saddle
#

Maybe look at the logs

native tide
#

nothing on the logs

#

Yup it just keeps going and then gives me the "took too long to respond"

#

Found this question on SO

#

no solution though

maiden valley
#

Hello! I need some advice setting up a flask+uwsgi app

#

Been trying for more than 12h in a row! any experts around?

#

@everyone ?

jovial vapor
#

hello

#

is there a way to return an image and json data in one response ?

#

using flask

native tide
#

I have a really basic html/php form system. The user can submit their name, and message. To prevent spam I want to add a "cooldown" like feature that disables the user from continually entering bs into my form. How would I go about doing this?

sharp briar
#

use ip or session or cookie

lost saddle
#

In your database or redis or whatever $_SERVER["REMOTE_ADDR"] save this and the creation time with the name-message

#

When the user sends another post request, check if the remote address is been used before, if yes check if it is still on cooldown( something like current_time - last_entry.time > cooldown: allow)

#

If not uhhh

#

return 429 or smt

#

This is just how would you do with ip I guess

#

You can use session or cookies but they are rather easier to create a workaround

candid basalt
#

@native tide I did not work with flask all that much, but it may depend on the command you use to run it with. It should accept connections from the public interface, not from 127.0.0.1

#

@maiden valley Don't ask to ask, just ask your question. =]

#

@jovial vapor It depends. You can try to return base64-encoded image as a part of your json response.

#

@native tide depends on the setup. You can save the time and date of the last message by username and check it for every new submit if it's recent or not.

maiden valley
#

@candid basalt Thanks! :]

#

So, I am trying to configure Flask + uWSGI + NGINX, and I used to be agle to route the app folder with @app.route('/'), and access it with www.example.com/myapp

#

but now it only works if I route it like this: @app.route('/'myapp/)

#

I tried a hundred thousand configurations for ini file and nginx 'sites-enabled/default'

#

including mounting the app with
manage-script-name = true
mount=/myapp=myapp:app

#

in the ini file, without success!

#

with previous apps I was using the "ugly hack" SCRIPT NAME = /myapp and uwsgi_modifier1 30; in the nginx default file

#

the only thing that differ from the methods is that I was using python 2 before, and now python 3, and I found this thread:

#

Any thoughts?

maiden valley
#

Thank you for whoever will read this 😃

maiden valley
#

Solved it guys, I had a stupid backup ini file that was overriding the changes on the one I was modifying, thank you anyways!

elder nebula
#

Should I ignore this
[DOM] Input elements should have autocomplete attributes (suggested: "current-password"): (More info: https://goo.gl/9p2vKq) <input type=​"password" name=​"password" required id=​"id_password">​

quiet solstice
#

It would be better to implement it.

elder nebula
#

But it's django form

#

thing

#

Admin site

#

I am trying to find bugs / glitches / weaknesses

quiet solstice
#

Django's PasswordField doesn't add this automatically?

elder nebula
#

All my django admin sites gives this same error

#

or its in verbos

#

Verbose

quiet solstice
#

It's not an error, it's a suggestion by chrome to improve the page.

elder nebula
#

ok

#

So can it be a security hole?

quiet solstice
#

No

#

This is just something that makes it easier for people to use the password form

elder nebula
#

ok

#

Thanks

#

I try hacking my websites, I don't know what's the point in that

quiet solstice
#

Unless you modified the django admin forms I wouldn't worry about those.

elder nebula
#

I haven't

native tide
#

Hey guys anyone here well versed in domain name zone dns configuration?

#

Or knowledgeable?

native tide
#

@candid basalt i ended up running it on heroku and it opened it for everyone

opaque ice
#

What's the best way to make an <img> zoomable and draggable? Tried "wheelzoom" and some other google results but didn't really work.

Basically I have a large image of a graph that I want to be able to follow by dragging on the image with the mouse as well as zooming in and out on it.

native tide
#

2 things

#
  1. Lets say I run a Flask server on Heroku. Is it possible that when I go to a specific url (on the flask/heroku server so like http://[my app name here].herokuapp.com/solve) it opens another tab on my browser?
#

browser as in the browser I used to go to the http://[my app name here].herokuapp.com/solve

#
  1. How can I set a custom domain for my heroku app? So I want the url instead of http://[my app name here].herokuapp.com/solve it goes to http://dominus.com/solve. Is it modifying the host file?
candid basalt
#

@native tide

  1. Opens new tab when you visit the url by copypasting it into the browser address bar? Probably no.
  2. For services like heroku hosts approach may or may not work depending on how they handle incoming requests. There are routers involved, so it will probably not work without bought domain you own.
native tide
#
  1. Naa like using the webbrowser module. So I guess i go to http://[my app name here].herokuapp.com/solve and it does a redirect to another url
#
  1. So I have to get my own domain. Then what?
#

@candid basalt

candid basalt
#

With 1) I'm still not sure I follow.

#

With 2) Heroku docs should have info how to do it. I did not work with Heroku all that much.

native tide
#

Ahh ok

#

How can I then go to https://twitter.com/ for exmaple

#

Nevermind I got it to work

tough star
#

How I redirect the user to another flask page with on_click in html?

tough star
#

Can't I use url_for?

candid basalt
#

To provide an url into the JS function - yes.

#

To do a redirect without JS - probably not.

native tide
#

How can I format the return content on flask?

oblique vault
#

i want to learn web dev with py. djange or flask? which one is better?

hallow moat
#

it depends

#

what are you trying to do ?

lapis heron
#

guys, do you have any idea why test_text_content passes in this test case

from django.test import TestCase
from django.urls import reverse
from .models import Post


class PostModelTest(TestCase):

    def setUp(self):
        Post.objects.create(text='just a test')

    def test_text_content(self):
        post = Post.objects.get(id=1)
        expected_object_name = f'{post.text}'
        self.assertEqual(expected_object_name, 'just a test')

but if I add another test case, where I create another object in the same model Post, the first test case fails?
this is the second test case:

class HomePageViewTest(TestCase):

    def setUp(self):
        Post.objects.create(text='just another test')

    def test_view_url_exists_at_proper_location(self):
        resp = self.client.get('/')
        self.assertEqual(resp.status_code, 200)

    def test_view_url_by_name(self):
        resp = self.client.get(reverse('home'))
        self.assertEqual(resp.status_code, 200)

    def test_view_uses_correct_template(self):
        resp = self.client.get(reverse('home'))
        self.assertEqual(resp.status_code, 200)
        self.assertTemplateUsed(resp, 'home.html')

I'm following tutorial from Django for Beginners book

#

this is the result ```
E

ERROR: test_text_content (pages.tests.PostModelTest)

Traceback (most recent call last):
File "/home/standa/PycharmProjects/rango_project/pages/tests.py", line 13, in test_text_content
post = Post.objects.get(id=1)
File "/home/standa/PycharmProjects/rango_project/venv372/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/standa/PycharmProjects/rango_project/venv372/lib/python3.7/site-packages/django/db/models/query.py", line 399, in get
self.model._meta.object_name
pages.models.Post.DoesNotExist: Post matching query does not exist.


Ran 7 tests in 0.084s

FAILED (errors=1)```

hallow ferry
#

I'm trying to deploy a django website on a LAN network/intranet sort of thing. Right now the only way to access the site is through this address: 192.XXX.XX.XXX:8000, but I want others on the same network to be able to access it through putting 'intranet/' in a web browser, is it possible to redirect it?

steel flicker
#

hello

#

any experienced web scrapers here?

rigid turtle
#

Just ask your question @steel flicker

#

There are, but they may or may not be online and they're not going to reply unless they know what you're asking

#

@hallow ferry That sounds like a networking issue. You need to configure the client's DNS to resolve "intranet" to "192...".

dusk light
#

So I'm trying to make an API with a database I have

#

I'm not really sure how should I structure the endpoints, though

#

let's say I have a list of users. As far as I understand, the endpoint /user should return the full list of users, while /user/user_id should return a specific user

#

however, what happens if the user list is really big? Wouldn't that make it too slow?

lost saddle
#

make it with pages

#

With filters

#

/user?sex=male&age=24&is_god=False&page_item_count=12&page=10

fathom prism
#

@dusk light , as @lost saddle mentioned, use pagination when you query and add it into the URL as a parameter. I'd suggest paginating on the database level instead of the client side javascript

uneven jasper
#

Okay, thanks

#

What would be the best way to store survey data with flask?

kindred cosmos
#

In a database

uneven jasper
#

Could I use variables?

#

(The data doesn't need to be permanent)

kindred cosmos
#

I don't understand

#

You would have to use variables

uneven jasper
#

So I could just store it in a variables like this? :

gender = "Male"
name = "Jeff"

kindred cosmos
#

You lost me. I don't understand what you are trying to do

lost saddle
#

REEEEEEEEEEEEEEEEEEEdis

uneven jasper
#

Ok, sorry. Let me clarify some things.

#

I'm just trying to get information from a survey that I make and store it (I don't care how, I only need the data until the user gets the results.) Then use that data from the survey to pick a product from amazon and give them the link.

lost saddle
#

When does the user get the result

#

How does the user get the result

#

Where does the user get the result from

uneven jasper
#

?

#

The user gets the result at the end of the survey.

#

They get a amazon referral link

#

They get the result from us, after our system decides what they should get based off survey informatin.

#

I'm just asking how I should store the data.

lost saddle
#

You don't store any data

#

You get it from the form

#

You put it inside your get_result_from_user_data function

#

And return the result

#

There is no storing involved

#

Everything happens in a view

uneven jasper
#

Okay

dusk light
#

Still though, any parameter like that would be optional for querying, so someone who doesn't specify any parameter like that would still have to deal with waiting

uneven jasper
#

?

dusk light
#

just as a comparison in the API I've made (which is just a flask-restplus hello world with a few modifications so it queries my database), querying a specific user takes about 20ms, while taking the whole user list takes 5 seconds

#

I understand that I can use parameters so queries can only get what they need, but my issue is what should I offer in the endpoint by default

#

Oh, wait

#

I misunderstood what you told me about pagination

#

apologies

lost saddle
#

Parameters can have defaults

#

/user means /user?page=1 under the hood

fading lake
#

Does anybody know how i can access the equivalent of app.env in a Flask Blueprint?

#

Of course, asking for help = immediately finding a solution

#

If anyone else has this issue, import current_app from flask, and use that as a reference to your primary app, that will have the env variable

elder nebula
#

I want to create image gallery like this. The rows are always equal and dont leave empty spots. I got it working, but the problem id that, I use django and the images gets uploaded with django, and the classes stay always the same, second problem was that the images stays always on the same row.

#
<div class='pics_in_a_row'>
    <div class='img1'>
      <img src='img1.png'>
    </div>
    <div class='img2'>
      <img src='img1.jpg'>
    </div>
    <div class='img3'>
      <img src='img3.jpg'>
    </div>
  </div>```

```CSS
img {
  width: 100%;
  height: auto;
  vertical-align: middle;
}

.pics_in_a_row {
  display: flex;
}

.img1 { flex: 1.3344; }
.img2 { flex: 1.3345; }
.img3 { flex: 0.7505; }
.img4 { flex: 1.5023; }
.img5 { flex: 0.75; }

.pics_in_a_row {
  margin: 25px 0;
}

.pics_in_a_row > div:not(:last-child) {
  margin-right: 2%;
}```

THIS IS CREATED BY Pat McKenna.
#

So I need Javascript code or something to put the right flex class for the image, order to fit to the line.

uneven jasper
#

For some reason this
`
<h1>Click 'Continue' to get started.</h1>

<a href=”/form1”><input type=”button” value=”part1”></a>

#

Is showing this

#

And when I click the textbox it gives me a 404 error.

#

`from flask import *
#in the form action form action="", put the location of your cgi script and the value of the textbox will be passed to the cgi script. eg.
import cgi
import jinja2

app = Flask(name)

@app.route('/')
def home():
return render_template('index.html')

#survey part 1

@app.route('/form1', methods=['GET','POST'])
def part1():
return render_template('part1.html')#required, otherwise it would render part2
name = request.args.get('name') #name
print(name)
gender = request.args.get('gender') #gender
print(gender)
return render_template('part2.html', gender=gender, name=name) #no extra comment at end.

#survey part 2 -- GENERAL hobbies and intrests. See project overview.
@app.route('/form2', methods=["GET","POST"])
def part2():
genhobby1 = request.args.get('hobbieslist1')
print(genhobby1)
genhobby2 = request.args.get('hobbieslist2')
print(genhobby2)
return render_template('part3.html')

if name == "main":
app.secret_key = 'super secret key'
app.debug = True
app.run()

#1 queston per page

#Dynamic questions
`

versed lotus
#

make sure you're using the correct characters for your quotation marks in your html. it looks like you're using instead of "

rocky wyvern
#

Hello. Is this the right place to ask about using Beautiful Soup?

hallow moat
#

@rocky wyvern just ask

steel tiger
#

For anyone trying to make a REST api with Flask, here is a really useful tutorial: http://polyglot.ninja/rest-api-best-practices-python-flask-tutorial/

cursive cairn
#

Total noob: How do I call a function only after a specific event (uploading data) has been performed?

#

In Flask

kindred gate
#

make a request to a backend Flask URL with the function using JavaScript

cursive cairn
#

Could you give an example?

fathom prism
#

@cursive cairn , what kind of action are you attempting to perform? Is it a clientside UI interaction or a serverside processing action?

cursive cairn
#

@fathom prism Render some graphs upon uploading some data

fathom prism
#

@cursive cairn , is the user "uploading" data via a POST request to your web server and getting a HTML page or JSON response back?

cursive cairn
#

Uploading via POST. I want to upload data and render the graphs on the same page, directly after data has been uploaded

fathom prism
#

@cursive cairn, what framework are you using?

  1. User uploads to your endpoint /POST (e.g. /upload)
  2. <Do stuff to your file> (save to database, parse, etc)
  3. Return a JSON payload via ajax
  4. Have your javascript perform some sort of graph rendering
cursive cairn
#

Flask, Flask-Upload. Plotly.js for graphing.

fathom prism
#

The example on the flask upload doc is the exact one you could follow

@app.route('/upload', methods=['GET', 'POST'])
def upload():
    if request.method == 'POST' and 'photo' in request.files:
        filename = photos.save(request.files['photo'])
        rec = Photo(filename=filename, user=g.user.id)
        rec.store()
        flash("Photo saved.")
        return redirect(url_for('show', id=rec.id))
    return render_template('upload.html')

https://pythonhosted.org/Flask-Uploads/

Replace the returns with a jsonify(your response)

cursive cairn
#

To render the graphs on the same page would I just redirect to the same page, but with new information?

fathom prism
#

No redirecting of pages needed. Your javascript would make an AJAX call to the /upload URL

cursive cairn
#

Oh wow. I didn't even know AJAX existed. Learn something new everyday. Thanks! 😃

fathom prism
#

Np, best of luck on your journey

cursive cairn
#

Thanks!

#

Do you have any resources you'd recommend on learning to build webpages, specifically on Flask?

cursive cairn
#

Wow! Thanks so much!

elder nebula
#
x = document.getElementsByClassName("img1");

    $("img").each(function() {
        
        height = this.naturalHeight;
        width = this.naturalWidth;
        ar = (width / height);
        console.log(height + " x " + width + " = " + ar * 2);
        var element = document.getElementsByClassName("img1");

        for (var i = 2; i < element.length; i++) {
            var element = document.getElementsByClassName("img1");
            for (var i = 0; i < element.length; i++) {
                element[i].style.flex = ar * 2;
            };
        };
    });```
#

So What I am trying to do, is get every images height and width. Then divide it (width / height) and put that in the div what is .img1

#

Example: Html <div class="img1"> <img src="butterfly.jpg"> </div> <div class="img1"> <img src="butterfly.jpg"> </div> <div class="img1"> <img src="butterfly.jpg"> </div> <div class="img1"> <img src="butterfly.jpg"> </div>

#

So put that image width divided by height to img1 div as a flex.

#

Output: <div class="img1" style="flex: 1.00 1 0%;"> <img src="butterfly.jpg"> </div> <div class="img1" style="flex: 1.00 1 0%;"> <img src="butterfly.jpg"> </div> <div class="img1" style="flex: 1.00 1 0%;"> <img src="butterfly.jpg"> </div> <div class="img1" style="flex: 1.00 1 0%;"> <img src="butterfly.jpg"> </div>

#

so the problem is:
It prints out the last third images height / width.

sleek tartan
#

Hello, I'm currently trying to learn to use Flask and I'm trying to do so following best practices.

I am currently trying to add a bootstrap navbar and I want to give the template a list of links to add to the navbar. I want this navbar to appear on all pages of the site, but I'm not sure how to go about doing that.

From what I can tell I could create a list called navLinks or something and pass it as a parameter to the render template function, but I want it to be global & it seems like bad practice to add it to every call of the render template because the context that you pass should be specific to the page being rendered.

I have been working from this tutorial, http://flask.pocoo.org/docs/1.0/tutorial/, and I'm currently modifying things to use bootstrap and get a better understanding of how Flask works.

still briar
#

Are you using templates for your html? In that case you can create a base template that will always contain the navbar, which all pages include.

bold lichen
#

make your main page as template.html
then your other pages can reference that using

using the Jinja templating language http://jinja.pocoo.org/docs/2.10/
Pretty sure flask ships with it.

https://www.youtube.com/watch?v=QnDWIZuWYW0&index=3&list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH&t=0s explains it i think.

In this Python Flask Tutorial, we will be learning how to use templates. Templates allow us to reuse sections of code over multiple routes and are great for ...

▶ Play video
#

@sleek tartan

sleek tartan
#

Yes I am using templates

I have a base template that contains the following include

<header>
  {% include 'base/navbar.html' %}
</header>

My navbar.html contains

<nav class="navbar navbar-expand-sm bg-dark navbar-dark sticky-top">
    <a class="navbar-brand" href="#">
        <img src="{{ url_for('static', filename='Images/nav_icon.png') }}"width="30" height="30" class="d-inline-block align-top" alt="">
        Baker Codes
      </a>
    <ul class="navbar-nav">
        {% for link in navLinks %}
        <li class="nav-item">
        <a class="nav-link" href="{{ link[1] }}">{{ link[0] }}</a>
        </li>
        {% endfor %}
    </ul>
</nav>

This currently works for the index page, but not any others.

uneven jasper
#

In python the quotation marks make a string green. In html they're not. I'm using atom.

proper hinge
#

Doesn't mean something is wrong. They're different languages so Atom uses different syntax highlighting rules for them

#

Though the quotes for button look wrong

#

You should use the "straight" quotation marks instead of these

sleek tartan
#

I kind of figured out my issue.

In my init file I used a context processor

    @app.context_processor
    def inject_navList():
        navLinks = {'links' : [{'name' : 'Home', 'url' : url_for('index')}, {'name' : 'Hello World', 'url' : url_for('hello')}]}
        return  dict(navLinks=navLinks)

That allowed me to access the dictionary without passing it to the render template function.

Anyone more familiar with flask know any best practices for where to declare context_processors?

civic tartan
#

@terse portal this is a Python web development chat

native tide
#

Hello,
I like to create a website with flashcards, but I don't have idea how to create a models with it.
Do you think that such a thing makes sense?

from django.db import models

class FirstFlashcard(models.Model):
    
    LANGUAGE_CHOICE = {
    ('PL', 'Polish'),
    ('EN', 'English'),
    }
    
    first_language_choice = models.CharField(max_length = 10, choices = LANGUAGE)
    flashcard_text = models.CharField(max_length = 50)

    class Meta:
        verbose_name_plural = 'First Flashcard'

    def __str__(self):
        return self.flashcard_text
    


class SecondFlashCard(models.Model):

    LANGUAGE_CHOICE = {
    ('PL', 'Polish'),
    ('EN', 'English'),
    }
        
    second_language_choice = models.CharField(max_length=10, choices = LANGUAGE_CHOICE )
    first_language_text = models.ForeignKey(FirstFlashcard, on_delete=models.CASCADE)
    second_flashcard_text = models.CharField(max_length = 50)
    
    class Meta:
        verbose_name_plural = 'Second Flashcard'

    def __str__(self):
        return self.second_flashcard_text

proper hinge
#

Why do you have two separate models? One for each side of the flash card?

native tide
#

@proper hinge I wanted to create one model, but I do not know how to make choice_field also contain the possibility of entering text (specific text to a specific language).

#

@proper hinge at the moment this is only a concept and I would like to come up with the most reasonable idea

proper hinge
#

I'm not familiar with Django forms honestly

#

But just from the perspective of model design having two models seems redundant

native tide
#

@proper hinge I think you have right. In that case, I must think how to implement it in one model in a logical way, right way.

proper hinge
#

Some ideas:

  • In one model, make text fields for the front and back sides as well as language fields.
  • Have one model with a single text and language field, then create a new model which "pairs up" two flashcard models using foreign keys.
#

Building on the first idea, instead of two language fields, you can have one that is like PL_EN or EN_PL so you can deduce the language of each side from a single field.

#

Though that doesn't work too well if you plan on having more than just those two languages

#

It's easier to add support for more languages when fields are separate

native tide
#

@proper hinge At the moment I focus only on two languages, but probably in the future I would like to add more

#

@proper hinge I will try to implement it in some way and share the result. Thank You for advice!

proper hinge
#

You're welcome

lost saddle
#

Why not have just one flashcard model without language select and just have il8n

lost saddle
#
>>> e.aggregate(p=Count(F('likes')))
{'p': 51}
>>> e.aggregate(p=Count(F('dislikes')))
{'p': 21}
>>> e.aggregate(p=Count(F('likes'))-Count(F('dislikes')))
{'p': 0}
#

🤔

#
>>> e.aggregate(p=Count(F('likes')))
{'p': 51}
>>> e.aggregate(p=Count(F('dislikes')))
{'p': 21}
>>> e.aggregate(p=Count(F('likes')-F('dislikes')))
{'p': 1071}
>>> e.aggregate(p=Count(F('likes'))-Count(F('dislikes')))
{'p': 0}
>>>
#

I'm lost

vagrant adder
#

@uneven jasper you shoud use {{ url_for(function_name) }} instead of /function_name

#

btw you cannot use multiple return statements at same indentation

#

basics of python

lost saddle
#

btw you cannot use multiple return statements at same indentation

#
import random
def f():
    if random.randint(0,1):
        return 0 # 8 space
    else:
        return 1 # 8 space```
native tide
#

So I'm making a backend using flask and hosting it using heroku

#

the idea is that a user submits certain keywords to the program

#

when that keyword matches text found somewhere in a external file

#

that is hosted in the backend

#

it needs to alert the user

#

So i know what i wanna do

#

basically im confused on

#

how flask is going to manage the users seperately

#

so like if user 1 has keyword "ok" and user 2 has keyword "bye"

#

and if the program finds the work "bye" in the external file

#

how will it only return the alert to that user

gritty carbon
#

Hey guys, i wanna make a form that can edit multiple instances of some object with different values with 1 click

#

each row is different instance, i want to put values in 'stan' collumns and just click blue button to save values to objects

#

is that possible and if yes then how?

#

i tought that Formsets are solution but from what i understand it is when you want to provide single value to multiple objects is that right?

#

oh i frogot to mention that I'm using Django

wary mantle
#

Hey,
So... I'm working with Flask...
I was wondering on how you could do a custom form kind of thing, if that makes sense. I don't know how to explain it.
So like the user can write text, then add an image in-between, add code maybe, then continue writing. Like how they do it on Medium and on other blog sites. Something like what's in the image below.

brisk escarp
#

If i use django i won't be able to have asynchronous code right? So doing transactions with the database would make the website slower since it needs to finish the task before it continues running the code.
How could I avoid that? any suggestion would be appreciated

#

sry for my lack of experience if I said something wrong

gaunt blaze
#

i briefly looked into this it sounds like people are using celery

rocky wyvern
#

Does anyone know why using MySQL while hosting locally on windows would be a problem?

worthy compass
#

do you really have to go through two weeks of "app review" to post to a fb group?

rare oar
#

Hi all. How does everyone work with testing out their models in Django? Looking to learn about some more complicated things sub queries etc. Whats your work flow? Django shell?

wheat trellis
#

Hey guys

#

Anyone here had experience with lamdba with python..mainly authentication.

covert lagoon
#

Are there stuff like expessjs in python?

native tide
rare oar
#

Hey all with Django annotations, if I wanted to do a calculation later, is it something like this? Right now win_rate returns just 0 in my f-string as {win_rate:.2}

radiant river
covert lagoon
#

ty

fading lake
#

When using flask, is there a wrapper that can be used for when a session is destroyed?

#

I'm looking for a way to clear temporary files after a user leaves

opal leaf
#

looks like there are a couple of options, but its limited because session expiration seems to be handled by the db backend
a) delete them when the user logs out/some other manual trigger
b) occasionally check which users have not done anything for a while and clean them up
c) figure out if the db backend you use has a hook for it

fading lake
#

There isn't a db backend, it's all going to be working with image files

#

However, I think I've found a workaround that should do just fine, I'll just need to do some restructuring

#

Essentially, what I was thinking was, front end / smaller web app I'm working on now (partially for a class) would AJAX files at this backend, which would save them, allow the users to pick a function on a different backend (one that I've already made), and then ajax to my backend which would call the other backend and then save that response and give the frontend a url to display that.

I've narrowed it down to the user will pick a function and upload the image in one go, allowing me to save it for as long as it takes to make the response, then wipe it (or just keep it in a temporary file object), and then save the new one and have the front end make a request when it's loaded and delete it serverside.

#

It's terribly thought out, but the deadline isn't for another few months and I'm already making pretty strong headway into this

opal leaf
#

yeah i would just not tie the activity to the session directly. decouple it and just let the session access the status and results of the activity.
if you find out the user wont come back to download the file you can delete it, but otherwise just let your system process it and the user check any status/results by loosely associating their session with the activity [eg via an id]

#

this way you can just say 'all files created will be deleted within 1 hour' and if the user downloads it or not you still know its time to delete it

fading lake
#

Yeah that might be another good approach

#

I've never really dealt with file uploading or temporary files, so this is good practice

crisp flume
#

Hey folks, I am trying to learn web scraping and looking for more tutorials to do. Do you have any favorites you suggest I try?

vernal kraken
#

Anyone using aws S3 with flask and boto3? I am trying to set the output size before upload using PIL but its not working. Is there a special command anyone knows that will work?

native tide
#

I have a stupid question, Should i check for password confirmation in the frontend or the backend ?

#

I mean which is the best ?

vernal kraken
#

What are you handling it with?

#

ie flask or Django? I use flask, and these modules will do most of the work for you.
from flask_login import login_user, current_user, logout_user, login_required

#

and the PW hashing
from werkzeug.security import generate_password_hash,check_password_hash

native tide
#

I use django rest framework

#

I hashed the password , by confirm i meant 2 input fields named password and confirm password

#

I just asked which is the best practice to do it, in the front end (react native app) or the backend (django api server)

vernal kraken
#

Ah ok. I just do it on the frontend, and if its valid it commits the hash to DB:

    email = StringField('Email', validators=[DataRequired(),Email()])
    username = StringField('Username', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired(), EqualTo('pass_confirm', message='Passwords Must Match!')])
    pass_confirm = PasswordField('Confirm password', validators=[DataRequired()])
    submit = SubmitField('Register!')```
radiant river
#

im trying to override the allauth default template. The docs say For instance, the view corresponding to the account_login URL uses the template account/login.html. If you create a file with this name in your code layout, it can override the one shipped with allauth. Is this saying i create a module called account and a template in it called login?

covert lagoon
#

How would I use the redirect function to redirect to my / page in Flask

#

I've tried

#

redirect(url_for('/'))

#

Oh just redirect('/') will work

silver crest
#

how can i use web development for python

#

???

ripe pecan
#

Look into Flask/Django

deft needle
#

Hey what do you think to use django with react for the frontend ?

sturdy sapphire
#

django and react is a good stack to work with

deft needle
#

Oh okay cool, thx @sturdy sapphire

junior shadow
#

I'm looking for some advice on the "djangonic" way of dealing with apps

#

what size functionality "should" be contained in one app; and what functionality should be split up

#

also, in a completely different direction, what framework is most commonly used to unit-test django http requests

shrewd sand
#

Has anyone got a way to handle keybbards on android and IOS effecting the website layout, making forms move wayy up

quaint ledge
#

hey i want to make a simple website with flask with basic things like info pages/blog posts and somewhere to upload files, where should i go to learn this stuff?

unborn terrace
#

@quaint ledge virtually any Flask tutorial, just google this and pick any

quaint ledge
#

ok

stark yarrow
#

How do I serve a file from flask to my home server? I want to be able to send a get request with a fpath and download the file. Is it possible? Will only run in my local network

native tide
#
ul {
    width: 100%;
    background: transparent no-repeat fixed 0% 100%;
}
#
<ul>
            
            <li><a class="active" href="RpmhdpSettingUp.html">Challenge 1</a></li>
            <li><a href="RpmhdpHNavbarBio.html">Challenge 2</a></li>
            <li><a href="RpmhdpColumns.html">Challenge 3</a></li>
            <li><a href="RpmhdpTables.html">Challenge 4</a></li>
            <li><a href="RpmhdpEditor.html">Challenge 6</a></li>
            <li><a href="Rpmhdp7.html">Home</a></li>
        </ul>
#

Anyone know why the CSS is not applying the ul?

#

This works but i'm not sure if it is the best way to do it, Any suggestions ?

#

btw using django rest framework

sonic harness
#

@native tide Aside from your indentation, everything looks good. Depending on what you are inheriting from, you may not need those arguments to super.

#

Does anyone have tips on how to reverse engineer an WebSockets based game? Is wireshark the way to go or nah? Firefox doesn't let you see what's being sent over the WS connection, does anyone know if chrome does?

uneven jasper
#

@vagrant adder I tried that and it gave me this error: jinja2.exceptions.UndefinedError jinja2.exceptions.UndefinedError: 'form1' is undefined

#

This is my code:

#

`from flask import *
#in the form action form action="", put the location of your cgi script and the value of the textbox will be passed to the cgi script. eg.
import cgi
import jinja2

app = Flask(name)

@app.route('/')
def home():
return render_template('index.html')

#survey part 1

@app.route('/form1', methods=['GET','POST'])
def part1():
return render_template('part1.html')#required, otherwise it would render part2
name = request.args.get('name') #name
print(name)
gender = request.args.get('gender') #gender
print(gender)
return render_template('part2.html', gender=gender, name=name) #no extra comment at end.

#survey part 2 -- GENERAL hobbies and intrests. See project overview.
@app.route('/form2', methods=["GET","POST"])
def part2():
genhobby1 = request.args.get('hobbieslist1')
print(genhobby1)
genhobby2 = request.args.get('hobbieslist2')
print(genhobby2)
return render_template('part3.html')

if name == "main":
app.secret_key = 'super secret key'
app.debug = True
app.run()

#1 queston per page

#Dynamic questions
`

#

This is index.html

#

`<h1>Click Continue to get started.</h1>

<a href='{{ url_for(/form1) }}'><input type="button"></a>
`

vagrant adder
#

When function hits the first return, funtion ends

#

Take a look at python basics

#

Also

#

{{ url_for('part1') }}

uneven jasper
#

Okay thank you.

strong igloo
#

Complete web noob here. I'm trying to get keystrokes on a webpage to python as the keys are pressed, I can see the request on each keystroke, but info print is always b''

<!doctype html>
<title>Testing</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
  $(document).keypress(function(e) {
    $.ajax({
        method: 'POST',
        url: {{ url_for('keypress') | tojson }},
        data: e.which
      })
  });
</script>
import flask

app = flask.Flask(__name__)


@app.route('/')
def index():
    return flask.render_template('base.html')


@app.route("/keypress", methods=["POST"])
def keypress():
    app.logger.info(flask.request.get_data())
    return flask.jsonify(result="TODO")


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

any pointers in the right direction would be appreciated 😛

#

figured it out, e.which to e.key in the javascript

#

follow up question.... how do I debug javascript

quiet solstice
#

You can use the browsers console for basic debugging.

#

It has breakpoints etc

strong igloo
#

oh neat, I did not know that!

quartz idol
#

Are there any guides you guys recommend for learning HTML/CSS?

cursive cairn
#

Can someone help me clear my confusion? I am trying to render graphs on a page after the user uploads data. I have a bunch of functions in Python that make the json needed for rendering the graphs using a Javascript library. What would be the most efficient way to pass uploaded data to my python functions and then the JSON back to Javascript without reloading the page? I assume I'll have to use AJAX?

unborn terrace
#

@cursive cairn if you do not want to reload yeah you have to use AJAX (or Websockets or stuff like that, but will be overkill).

#

You are probably better off simply reloading the page, that is not so bad tbh

cursive cairn
#

How do I send data from AJAX to Flask, run some functions, and then pass the data back without reloading?

unborn terrace
#

@cursive cairn create a Flask view that receive data (from a form or JSON for instance) and returns new data

#

And send a request to this view from within the page, using AJAX for instance

cursive cairn
#

yeah im refreshing the page

native tide
#

I'm making a progress bar..

#

is there anyway I can make it look cooler

#
    publish.css("""
      .pwnr-progressbar {
       border: 3px solid #bbbbbb;
       border-radius: 10px;
       height : 30px;
       background:#cccccc;
       overflow:hidden;
       display:inline-block;
      }
      .pwnr-progressbar-inner {
       height : 24px;
       padding:3px;
       padding-left:5px;
       font-size:17px;
       color:#005500;
       position:relative;
       background:#77ddee;
      }
      .pwnr-progressbar-eta {
       margin-left:3px;
       display:inline-block;
       position:relative;
       top:-10px;

      }
    """)
quaint ledge
#

how do i put my flask app online?

#

what

#

yea i know that

#

im asking how to put it on a domain

#

yeah...

#

im being told to use AWS but not sure how

#

also heard heroku but also heard its not good

red jetty
#

Is there a easy spinup for django? Like generic setup

#

Ive worked with php etc (drupal) for.. last decade.. Django sounds nice

rancid junco
#

I know this is silly, but I am trying to learn js, but I am a tad confused. So I made a json file that contains jokes, and I would just like to simply "lists " them on a site, like I want the question and answer to just show up in the center of the screen, and after a wait time, then show the next joke. Any idea how I can do this?

#

also these are the jokes

#

I just took them from the programming dad jokes github page, and turned them into a json file

rancid junco
#

nvm I think I figured it out

rancid junco
#

Nope

#

so does anyone know the best way to show two values, have a wait time, then show the next two in the json?

#

the wait time is not issue, its the showing the values

teal scroll
#

how do i send POST data without a form

radiant river
#

the django docs say
allauth ships many templates, viewable in the allauth/templates directory.

For instance, the view corresponding to the account_login URL uses the template account/login.html. If you create a file with this name in your code layout, it can override the one shipped with allauth.
so to override the all auth html do i create a module called account and a file called login .htm

radiant river
#

can i get some django

#

allauth help

#

man this is just not working

untold zealot
#

I'm a tad confused about backend web dev languages. How does a non OOP language like Python or JS work with back end stuff? Like I guess I'm just not seeing the capabilities of a scripting language besides making little kiddie scripts

grand musk
#

@untold zealot Python is an OOP language

#

python is FILLED with objects

untold zealot
#

yeah nvm I'm an idiot

quaint ledge
#

@teal scroll which self deployment option is the best? the descriptions arent that helpful

quaint ledge
#

what do cloud services mean when they say "instances"?

fathom prism
#

most likely a virtual machine

junior cloak
#

@untold zealot haha kiddie scripts, really? tell that to instagram, youtube, the entire machine learning and data science industries, the entire visual effects industry, many other things, etc. like any language there are areas in which it excels and areas in which it does poorly than others. and also like anything else, it's also dependent on the skill level of its user

#

@quaint ledge yes "instance" refers to a single virtual server of some sort. regarding deployment -- which is the "best" depends on your needs. do you already use aws or heroku or any of those? is there a budget for this project? do you want something that's easier to work with or more painful but cheaper? etc

quaint ledge
#

oh ok

junior cloak
#

@quaint ledge oh sorry, you said self-deployment. okay that's different, one can safely say that gunicorn + nginx is key

#

i would not bother with those other choices

quaint ledge
#

i decided to go with a virtual server

#

digital ocean

#

it seems good

#

seems cheap too

junior cloak
#

except that i am a huge fan of Caddy as a web server that is dead simple to use and performs about 80% as well as nginx and so yeah

#

DO is fine

#

is this for fun or work or intended to be running in production with users and whatnot soon

quaint ledge
#

its for fun

junior cloak
#

DO is fine, the obvious downside with any vps provider is that you now have to run the vps and all the crap on it

#

which is why i love heroku to death and use it for everything in development, but its costs are not conducive to growth in production

#

however its free tier is more than adequate for most projects while they are in development and then your entire deploy process consists of running git push heroku master rather than configuring a vps, linux, nginx, gunicorn, everything else

#

it's all tradeoffs depending on needs and goals and resources

quaint ledge
#

the free tier didnt seem that great and i think $5 is a good price for what im getting

#

and i dont really have a problem setting it up

junior cloak
#

for heroku? if you had lots of usrs it would be a problem because heroku's free tier has to spin the application down when it isnt being used much, so in production it wouldnt work. but in development it works fine since presumably you arent using the app for 24 hours each day

#

and when i am using it with the free tier and free postgres db it can still handle a couple thousand active [simulated] users

quaint ledge
#

id prefer it to be up all the time

junior cloak
#

but anyways

#

yeah totally, just asking. sometimes simplicity is important for people

#

then yeah the de facto thing to do would be ubuntu instance, nginx web server proxying to your python app which is using gunicorn

#

i would still perhaps recommend caddy because you can go from never having touched it to a production-ready server for your python app and automatic ssl in less than 10 lines of configuration and a few minutes

#

nginx is certainly the standard and is fantastic but it's much more complex

vagrant adder
#

guys i am making a little CRUD twitter-like app

#

where can i find ideas for user account html files

junior cloak
#

@vagrant adder ...as in like, design inspiration? or as in you know how it should look but not sure how to implement it? if it's the latter, then you need to either take a step back and dive into html/css, or you should use a ui library (bootstrap, bulma, whatever) that already has the html/css made and you just have to put them where you want

vagrant adder
#

as in idea

#

coding html is not a big worry

junior cloak
#

haha okay

#

just checking

vagrant adder
#

it's just that i'm not a creative soul

junior cloak
#

yeah that's the age old question, how should it be designed? and theres ever a perfect answer

#

i of course make note of how things are laid out that i think are welll done

#

and i spend lots of time on dribbble and visiting various design inspiration lists

vagrant adder
#

i thought of wix but wix is essentially markerstore template list

junior cloak
#

you thought of wix as in... you like how their user profile pages are designed? or what

#

wix does have some pretty well designed stuff on occasion

steel tiger
#

I have a view with an int at the end in routing, for example: ```py
@app.route('/some_view/int:id')
def some_view(id):
return f'Example result for id: {id}'


The only problem is that I would like to check in templating if the path is `/some_view/<int>` but do not know how to.
#

Basically what I need to do: ```py
if request.path == url_for('some_view', id=[NEED THIS]):

#

It will detect if the ID is anything.

#

The thing I am trying to achive is a navbar so I have to do it in templating FYI

steel tiger
#

Nobody? :(

vernal kraken
#

@steel tiger like pagination? You can grab a bootstrap example and there are a bunch of tuts on how to set it up with flask or Django

weak hazel
#

Hello!
Can anyone tell me how to start with Django.
Im intermediate in Python.

midnight timber
#

@weak hazel I've been following this recently

#

it's been fantastic

odd obsidian
#

Hello guys! Anyone with some knowledge of web.py that could point me in the right direction or give me some pointers how I should go about creating a lobby system, such like Kahoots, in the web.py framework?

quaint ledge
#

hey @junior cloak, do you know what they mean in this pic by "app key"?

junior cloak
#

@quaint ledge where on earth are you finding these tutorials

quaint ledge
#

DO

junior cloak
#

even this little snippet looks strange

#

but to answer your question

#

the secret key is just any random, hard to guess string

#

doesnt matter what it is, nor do you have to remmember it

#

just a very long intense password

#

it's used when flask needs to secure the cookies, sessions, etc

quaint ledge
#

where do i uhh get it

junior cloak
#

you never have to work with it yourself really

#

you make it up