r/pythonhelp • • Jul 12 '23

Google oauth with fastapi-users procedure

4 Upvotes

Hi, r/pythonhelp,
I have the first steps working for fastapi-users==12.0.0 with Google OAuth but I don't know what to do with the access_token once I get it from /auth/google/callback.

The fastapi logs show User <user_id> has registered and a new row is added into each table (user, oauth_account), so that's good.

So far I have:

  1. GET /auth/google/authorize which returns a JSON with an authorization_url.

  2. I navigate to that authorization_urland authenticate via the prompts at https://accounts.google.com/signin.

  3. I am redirected to /auth/google/callback?state=<some_token>&scope=<email, profile, user scopes>=0&prompt=consent, which shows {"access_token":<access_token>,"token_type":"bearer"}.

What am I supposed to do with that access_token? To access private endpoints do I need to include it in the header of every future request?

For this strictly google process, do I need to use any of the other endpoints (eg. /auth/jwt/login, /auth/register, /auth/request-verify-token, /auth/verify)?
How would I complete this process via the swagger docs? The Authorize form (OAuth2PasswordBearer) currently shows Token URL: auth/jwt/login and Flow: password). I don't need to change that at all right?


r/pythonhelp • • Apr 05 '23

How to use Python virtual environments in terminal mac?

4 Upvotes

Hello,

I have a few questions regarding Python virtual environments on Mac. I am running Python 3.11.2.

  1. Apparently, venv is installed with newer versions of Python, but when I type pip3 show venv, I get this message: WARNING: Package(s) not found: venv . So, I tried installing it:

  • pip3 install venv

  • ERROR: Could not find a version that satisfies the requirement venv (from versions: none)

  • ERROR: No matching distribution found for venv

So I installed virtualenv instead. Do I need to have the version of Python that I am trying to make a virtual environment with installed on my system? When I run:

virtualenv -p python3.9 env

I get the error message:

RuntimeError: failed to find interpreter for Builtin discover of python_spec='python3.9'

Even when I DO have the version of Python installed on my system when I run virtualenv and check the Python version, it's still running Python system default:

  • virtualenv -p python3.8 env

  • source ./env/bin/activate

  • python --version

  • Python 3.11.2 (system default)

Maybe I should just start from scratch, uninstall everything that has to do with Python on my system, and reinstall. How would I do this?

I have Python installed to these locations:

  • /Users/myname/Library/Python/3.8

  • /Users/myname/Library/Python/3.7

  • /Library/Frameworks/Python.framework/Versions/3.8

  • /Library/Frameworks/Python.framework/Versions/3.11

My .zshrc file has these Python paths:

  • alias python=/Library/Frameworks/Python.framework/Versions/3.11/bin/python3

  • alias python3=/Library/Frameworks/Python.framework/Versions/3.11/bin/python3

  • export PATH="/usr/local/bin/python3.11:$PATH"

I know I need to change permissions on my zsh shell. When I run:

  • sudo chown myname zsh

  • chown: zsh: Operation not permitted

I'm getting very frustrated.


r/pythonhelp • • Feb 19 '23

3 Simple Programming Tips for Beginner Python Programmers

4 Upvotes

As a new Python programmer, it can be easy to forgo syntax because this often seems less important. You often just want to solve the problem and do not worry about the sloppiness of the code. However, practicing good syntax from the beginning and slowly learning ways to improve your code syntactically can be very important in practice. In this video, I talk about 3 simple ways to instantly improve your code syntactically that are easy to remember and can help you have more professional-looking code in accordance with pep 8 standards.

1-) Organize imports accordingly

2-) Be cognizant of white space in your code

3-) Use f strings when possible (except for logging) as they are superior to previous forms of string formatting.

https://youtu.be/docjgO_1VCQ

Also please give the video a like and subscribe if you enjoy learning simple ways to improve your Python code. I have other videos on the channel that can help you as well!

Let me know if you have any questions or concerns. Thanks!


r/pythonhelp • • Sep 01 '22

Virtual Mouse in python

4 Upvotes

I need help trying to discover a way to use a virtual mouse in python. I want it to be able to interact and do events that my real mouse can do, but instead I can dictate the cords and activities it does. I see for pyautogui I can dictate what my real mouse does, but I want to create a mouse that is virtual in a sense. Thank you.


r/pythonhelp • • Jul 15 '22

Sorting data frame by column value

4 Upvotes

Hi there,

if anyone could help me out that would be greatly appreciated. I have been searching this error on the internet for a bit and cannot find anything.

I have a data frame that I am trying to sort by the column "age_of_shooter"

code:

df.sort_values("age_of_shooter" )

I am getting this error:

ValueError: No axis named age_of_shooter for object type Series


r/pythonhelp • • May 25 '22

Best practice for storing passwords (special case)

4 Upvotes

Hi there!
I'm writing a Python script that interfaces with an API that users can login to (that doesn't have API keys or anything like that). Really, it just requires a username, password, and URL.

For testing, I have been using a web page to make POST requests with this info back to my script (a Flask application). But if I'm going to make this public, I don't think users would be enamored with the idea of this info being sent in plain text over the internet (even HTTPS I know) and then also stored in plain text on my server that doesn't have enterprise-grade security.

How would you recommend I go about this? If I just wanted to use a password for authentication, I could just hash it and store that. But because I need the actual password to connect to this other API, I can't really do that because you can't decrypt SHA-256.

Any suggested methods/libraries/hashing algorithms that might do this job better? Ideally something that could also be implemented in JS on my web interface.

Thanks!


r/pythonhelp • • Apr 27 '22

Is it possible for a Python Script to automate tasks across multiple applications? (Context in post)

4 Upvotes

I'm new and still learning Python, so l am not sure how to necessarily ask this question properly.

Basically I am wondering is it possible to create a Python Script that will automate tasks across multiple applications?

For context, I am a product designer by day, and am wanting to automate some mundane tasks that involve performing some tasks in my 3D modeling software (Rhino), saving out that 3dm file, then taking the file and opening it in the rendering software (Keyshot) and performing some tasks/render save outs, then taking the png file and resizing and other tasks in Photoshop, and finally saving over the previous png. I know these applications can read Python, as they have built in Python Consoles for scripting. So I am sure worse comes to worse I just write scripts for each individual tasks. I am just hoping there’s a way (and not even necessarily for these specific applications) to have a Python script that can work across multiple applications.

I am not necessarily looking for exactly how to do this, unless of course someone is able to provide a script 😂. But more so, I am just wondering if this is even possible and if so, what is the terminology/name of the process of creating a script that works across multiple applications?

I have tried googling, but because I am not too familiar in this subject, I am struggling to find the proper words and terminology to search for a solution and learn how to script what I am wanting (if it’s even possible). TIA


r/pythonhelp • • Mar 23 '22

SOLVED I have a problem with reading from file

4 Upvotes
org = "hehe"
while org != "exit":
	org = input()
	with open("orgsList.txt", "r") as orgsList:
		if org in orgsList.read():
			print("Not this one")
		else:
			print("This one!")

So what I'm trying to do is to check if a string is in the file and if it is print "Not this one" but when I run the program the result is always "This one!" despite me typing the exact string that is in the file. The text file itself contains organizations names divided by paragraphs.


r/pythonhelp • • Mar 12 '22

Accessing Python Gmail API in a local app that isn't tied to a Google Cloud Platform project?

4 Upvotes

I'd like to write a small Python app that I can run locally to perform some maintenance on my Gmail account (specifically, managing filters). I understand that the Gmail API is very capable and can provide these functions via a convenient RESTful API.

I've looked at about a dozen Gmail API tutorials, and all of them start like this:

"Login to your Google Cloud Platform account, create a project, and authorize it to use the API..."

Or:

"Login to your Google Cloud Platform account, access Credentials, and create some OAuth 2.0 credentials for your GCP project..."

And Google's own page for creating API keys goes like this:

To create your application's API key:

  • Go to the API Console.

  • From the projects list, select a project or create a new one.

  • Choose Credentials. Click Create credentials and then select API key.

But I don't have or want to run my code inside a GCP project. All I want to do is to grant my locally-running Python app some credentials so that I can make RESTful API calls. I don't understand why all of these tutorials require anything associated with a GCP project.

Has anyone else encountered this issue? Is it even possible to access the Gmail API outside of a GCP project?

Thanks in advance.


r/pythonhelp • • Mar 01 '22

Make Python run on faster p-cores instead of e-cores in Spyder IDE

4 Upvotes

Hi hoping someone here has some ideas about this. I have stand alone Spyder, and a new 12700k Intel CPU. The CPU has 8 performance cores which run faster than the 4 efficiency cores it also contains. When I run a script in Spyder it uses an e-core to run Python, but I would prefer it to use a p-core. I tested this in VSCode, my command prompt, and even with R in RStudio and they all use performance cores to run the Code. I am using the same version of Python in Spyder as I am in CMD and VSCode (3.10.2, not the one that came with Spyder with it) Any idea how to force Spyder to run python on a P-core?

Thanks


r/pythonhelp • • Dec 18 '21

Xbox Api accessing the club posts for helping players.

4 Upvotes

Hi! I play a lot of destiny 2 and I built a bot to scan over the lfg chat application that they have to help people get through a activity called Garden of Salvation (a lot of players struggle in it and I like helping a lot.) But I want to taken it a step further and be able to scan over the Xbox club for posts using some kind of Xbox api. I have been looking for one but I have yet to find anything.


r/pythonhelp • • Nov 11 '21

How to speed up 7 nested loops?

4 Upvotes

I'm a mathematician. I'm wrote a small function to help me with calcluations that would be otherwise impossible to do by hand. There is a problem though: there are 7 nested loops that make it execute in minutes even for very small inputs.

The problem is the 2 deepest loops looks like this:

for i in N:
    for j in N:
        if int(a[j]) == i+1:
            x.append(str(j+1))
            continue

and:

 for j in b:
        i = int(j) - 1
        x.append(a[i])

I have no idea what to use to optimize this. I heard I'm supposed to replace loops with library functions that execute their code in C...

I will explain what the function does.

The functions takes (v,n), where v is a vector of permutations from the symetric group S_n. They are in string form, like this: "1234" - neutral element, "2134" = (12), etc. I don't care what form they are in, I can make them be a list of integers.

The function then takes each pair of elements (a,b) from the vector and tries to generate the group S_n. It outputs how many elements were generated by each pair.

The function tries to generate S_n by:

  • looping through all possible pairs of vectors (v,w) containing 0 and 1 of length range(d).

  • (in the first vector 0 means a, 1 means b)

  • (in the second vector 0 means nothing, 1 means reverse function)

  • inside the loop it combines (denoted with *) multiple copies of a and b in accordance with the 2 vectors. For example: v = [0,0,1] and w = [0,1,0] produces a * a^-1 * b.

for k in range(d):
    w.append(0)
    v.append(0)
    for i in range(2**(k+1)):
        for j in range(2**(k+1)):
            x.add(compSet(a,b,v,w,k+1))    # <- combines a and b according to (v,w)
            w[0] += 1
            for l in range(k+1):
                if w[l] > 1:
                    w[l] = 0
                    w[l+1] += 1
        v[0] += 1
        for l in range(k+1):
            if v[l] > 1:
                v[l] = 0
                v[l+1] += 1

I saw a video that showed it's thousands of times faster to use built-in numpy functions than for loops. I also found some complicated threads on 'how to make python run C code'.

Do you know how to optimize this function?

**Edit 2 XI 2021**
Newest code updated with all of the suggestions:

from functools import lru_cache
from itertools import permutations
from itertools import product
import time
import math
def tup2str(tup):
    try:
        return ''.join(map(str,tup))
    except:
        print('tup2str error', tup)
def tuplist2strlist(tups):
    try:
        return [tup2str(x) for x in tups]
    except:
        print('tuplist2strlist error', tups)
@lru_cache
def compSelf(a:tuple,i:int):
    if i==1: #a^-1
        return tuple(x+1 for x in sorted(range(len(a)),key=a.__getitem__)) # This statement might be wrong. 
    if i==0: #a^1
        return a
    raise ValueError("comp: i ==",i,"instead of 0 or 1")
@lru_cache
def compPair(a:tuple,b:tuple):
    return tuple(a[i-1] for i in b)
def compSet(a:tuple,b:tuple,v:list,w:list,k:int):
    #k = legth of v and w
    u = []

    for i in range(k):
        if w[i] == 0:
            u.append(compSelf(a,v[i]))
        else:
            u.append(compSelf(b,v[i]))

    x = compPair(u[k-2],u[k-1])
    for i in range(k):
        x = compPair(u[k - 1 - i],x)

    return x
@lru_cache
def compMass(a:tuple,b:tuple,depth:int):
    x = set()

    e = tuple(range(1,len(b)+1))
    x.add(e)
    
    for k in range(1,depth):
        v = [p for p in product([0, 1], repeat=k)]
        for i in range(2**(k)):
            for j in range(2**(k)):
                x.add(compSet(a,b,v[i],v[j],k))

    return x
def is_gen(a:tuple,b:tuple,depth:int):
    return len(compMass(a,b,depth))
def is_genMass(x:list,depth:int,is_check:bool,is_clear_out:bool):
    #tests all pairs in 'x' whether they generate S_n
    m = len(x)
    n = len(x[0])
    n_factorial = math.factorial(n)
    out = [[0]*m for _ in range(m)]
    count = 0
    max_count = 0

    

    if is_check == True:
        for i in range(m):
            for j in range(m):
                out[i][j] = is_gen(x[i],x[j],depth)
        is_wait_for_user = False
        for i in range(m):
            for j in range(m):
                is_divided = False
                for k in range(2,n+1):
                    if n_factorial % out[i][j] == 0:
                        is_divided = True
                if not is_divided:
                    print(tup2str(x[i]),"and",tup2str(x[j]),"don't generate a correct subgroup. Size: " + str(out[i][j]))
                    is_wait_for_user = True
                if out[i][j] != out[j][i]:
                    raise Exception("is_genMass: elements ",tup2str(x[i])," and ",tup2str(x[i])," generated unequal subgroups of size ",str(out[i][j])," and ",str(out[j][i]))
        if is_wait_for_user and n > 4:
            input('Input to continue. ')
    else:
        for i in range(m):
            for j in range(i,m):
                out[i][j] = is_gen(x[i],x[j],depth)
                
                
                
    if is_clear_out:
        print("Non-generating pairs:")
        for i in range(m):
            print("--------------------")
            for j in range(i,m):
                if out[i][j] != n_factorial:
                    max_count += 1
                    if x[i] == x[j]:
                        print(str(out[i][j]) + "/" + str(n_factorial) + " " + tup2str(x[i]))
                    else:
                        print(str(out[i][j]) + "/" + str(n_factorial) + " " + tup2str(x[i]) + " and " + tup2str(x[j]))
        print("Generating pairs:")
        for i in range(m):
            print("--------------------")
            for j in range(i,m):
                if out[i][j] == n_factorial:
                    count += 1
                    max_count += 1
                    if x[i] == x[j]:
                        print(str(out[i][j]) + "/" + str(n_factorial) + " " + tup2str(x[i]))
                    else:
                        print(str(out[i][j]) + "/" + str(n_factorial) + " " + tup2str(x[i]) + " and " + tup2str(x[j]))
    else:
        print("Non-generating pairs:")
        for i in range(m):
            for j in range(i,m):
                if out[i][j] != n_factorial:
                    max_count += 1
                    if x[i] == x[j]:
                        print(str(out[i][j]) + "/" + str(n_factorial) + " " + tup2str(x[i]))
                    else:
                        print(str(out[i][j]) + "/" + str(n_factorial) + " " + tup2str(x[i]) + " and " + tup2str(x[j]))
        print("Generating pairs:")
        for i in range(m):
            for j in range(i,m):
                if out[i][j] == n_factorial:
                    count += 1
                    max_count += 1
                    if x[i] == x[j]:
                        print(str(out[i][j]) + "/" + str(n_factorial) + " " + tup2str(x[i]))
                    else:
                        print(str(out[i][j]) + "/" + str(n_factorial) + " " + tup2str(x[i]) + " and " + tup2str(x[j]))
    probability = count / max_count
    print("Probability: " + str(count) + "/" + str(max_count) + " = " + str(probability))
def is_genMass_Self(x:list,depth:int,is_print:bool): #todo
    #tests all pairs of the same element in 'x' whether they generate S_n

    m = len(x)
    out = []

    for i in range(m):
        out.append(is_gen(x[i],x[i],depth,is_print))
    
    if is_print == False:
        print("Generating pairs:")
        for i in range(m):
            if out[i][0] == True:
                print(out[i][1] + " " + str(x[i]) + " and " + str(x[i]))
        print("Non-generating pairs:")
        for i in range(m):
                if out[i][0] == False:
                    print(out[i][1] + " " + str(x[i]) + " and " + str(x[i]))
    print("WARNING: This function might be wrong.")
def gen_longest_cycles(n:int):
    z = set()

    for p in permutations(range(1, n+1)):
        z.add(tuple(p[(k+1)%n] for j in range(n) for k in range(n) if p[k] == j + 1))

    return sorted(z)
def gen_permutations(n:int):
    return sorted([tuple(p) for p in permutations(range(1, n+1))])



n = 5
depth = 5
print(tuplist2strlist(gen_longest_cycles(n)))
x = time.perf_counter()
is_genMass(gen_longest_cycles(n),depth,True,True)
x = time.perf_counter() - x
print("Time:",str(x))

r/pythonhelp • • Nov 07 '21

SOLVED I'm looking to speed up my g-code editor

4 Upvotes

I am currently writing a program to edit my g-code for my 3D printer I'm wanting the printer to move the print head out of the way of the print at the completion of every layer and then move back to position. The code that I have written works but it's taking a really long time for the code to go through the entire file. I've attached my g-code file with the code.

Any tips on better commenting code are appreciated as well.

file_name = "test_goproholder.gcode" # put your filename here z=0 newline=['\n']

with open(file_name, 'r+') as f:

new_code = ""            # where the new modified code will be put
content = f.readlines()  # gcode as a list where each element is a line

for line in content:
    gcode = line.strip('\n').split(" ")  # seperates the gcode from the comments
    try:                                 #searches for a Z layer height callout and sets our operator equal to the callout
        if 'Z'== gcode[4][0]:
            z = gcode[4][1:]
    except:
        if line.startswith(";LAYER:"):      #searches for a layer height callout
            insert1=[f'\nG0 X1 Y290 Z{float(z)+10}\n']
            insert2=['G4 P5000']
            gcode= gcode+insert1+insert2
    gcode=gcode+newline
    new_code+=''.join([str(element) for element in gcode])
    print(new_code)
print(z)
f.seek(0)
f.write(new_code)

Here's and example of my test code:

G1X66.43Y39.519E218.93118

F600 E-1

;LAYER_COUNT:56

;LAYER:0

M107

G0 F2625 X36.605 Y37.768 Z0.425

;TYPE:SKIRT

G1 F600 E0

G1 F900 X37.439 Y37.1 E0.03559

G1 X37.875 Y36.806 E0.05311

G1 X39.165 Y36.079 E0.10243

G1 X39.616 Y35.868 E0.11902

G1 X40.498 Y35.536 E0.15041

G1 X40.996 Y35.393 E0.16767

G0 X64.468 Y39.131

G0 X64.477 Y39.032

;TIME_ELAPSED:466.669759

;LAYER:1

M140 S60

M221 S100 T0

M106 S68

;MESH:

G0 F6562.5 X64.477 Y39.032 Z0.675

;TYPE:WALL-INNER

G1 F600 E218.89162

G1 F1800 X65.145 Y39.131 E218.90485

G1 X65.806 Y39.296 E218.9182

G1 X66.43 Y39.519 E218.93118


r/pythonhelp • • Nov 03 '21

A python script or program to find unregistered domain name

4 Upvotes

Hi I'm launching a new business & struggling to find a domain. The domains that seem sensible is way beyond the scope of this small business. So, I'm looking for a script or a program that uses every word from the dictionary/ uses 2 words together with a dotcom & searches on the web to see if that name has a website registered. & If it finds that there is no name registered for a perticular domain it will add to a database/ text file. So, we can find a suitable name among those.


r/pythonhelp • • Oct 08 '21

HOMEWORK AIm doing computing in HS and don't know what the problem, with the code is, an the teacher aint in, Anyone Know?

Thumbnail
gallery
4 Upvotes

r/pythonhelp • • Oct 05 '21

I have a hard time to figure out why it gives me "TypeError: unsupported operand type(s) for -: 'int' and 'str'"

Post image
4 Upvotes

r/pythonhelp • • Oct 04 '21

SOLVED Please teach me since my "teacher" won't.

4 Upvotes

I have already gotten this answer to a quiz wrong and there's no changing the grade. So there's that. But this was the question.

Write an if statement that assigns 0 to x if y is equal to 20.

My answer was
if number > 19 and number < 21:
       print('x=0')

Obviously that was wrong. Now I asked what it should have looked like, since I clearly don't know, and all they told me was that
== <-- double-equal sign is equality operator
= <-- single equal sign is the assignment operator

So what should it look like?


r/pythonhelp • • Sep 05 '21

HOMEWORK I was testing my code. It gave a syntax error to the print part. I don't know why. Can you guys help please?

Thumbnail
gallery
4 Upvotes

r/pythonhelp • • Aug 26 '21

I cannot use any libraries on Linux

Thumbnail
gallery
4 Upvotes

r/pythonhelp • • Aug 13 '21

How can i achieve this.. without library?!

Post image
4 Upvotes

r/pythonhelp • • Jun 16 '21

I just received code for a reddit bot and I don't know how to use it! Can it be web hosted? Does it need to be on a PC running 24/7? More noob questions likely.

4 Upvotes

Hello! I'm sorry if this isn't the right place to post, let me know and I'll pack up my 1st world problems and leave.

So I received a shiny new bot that pulls all the daily word prompts for the month from ObjectWriting.com, and posts them in order each day to my new sub r/DailyObjectWriting.

Here is the github link: https://github.com/impshum/Reddit-Daily-Writing-Object

How do i use it?? Does it run off github or do i download it? The requirements txt says i need beautifulsoup4, PRAW, Configparser, and schedule.

If all these programs or files or libraries need to be installed, does that mean my PC needs to be on 24/7 to run the bot? Can it be run from a site like pythonanywhere.com?

In time i know i can understand all of this competently, but - having no experience in coding - it's overwhelming at the moment.

Any help you can give is greatly appreciated.


r/pythonhelp • • May 15 '21

How to selectively print lines of text from an external file if they meet certain factors

4 Upvotes

Sorry for the vague titles, I wasn't sure how to word the question

My goal is to print lines if they are set as incomplete so if:

a = incomplete

b = complete

c = complete

d = incomplete

etc.

then the file would be read and print 'a' and 'd' on seperate lines

Thanks for any help, Im kinda a noob at python


r/pythonhelp • • May 01 '21

HOMEWORK how to run python file on web browser like HTML

4 Upvotes

so I want to know that how to run python file on web browser like HTML file with the same python code.


r/pythonhelp • • Apr 29 '21

Help with pyqt5

4 Upvotes

I'm new to Python and QT5. Overall I have the UI setup I want and can get the signals to wrok, i.e. they print something to the console, but I don't know how to create a .txt output when I press the "Print" button that includes the changes in the comboboxes/input into the inputdialogbox. Essentially I don't understand how to save or access the changes or inputs to my widgets.

https://pastebin.com/qkfHZGa0