3

i have written script to create users using csv file. i have to check the sso username is valid or not using an api request as well and its written in _validate_user function. To make the api request i'm using urllib3. Sample code provided below.

import csv
import urllib3.request
from django.contrib.auth.models import User

def _validate_user(sso_username):
    http = urllib3.PoolManager()
    fl_name = '<url>' + sso_username
    site_data = http.request('GET', fl_name)
    _data = site_data.data
    print(_data)

FILENAME = r'./csv/usernames.csv'

with atomic():
    with open(FILENAME, 'rt',  encoding='utf-8-sig') as f:
        reader = csv.DictReader(f)
        for i, row in enumerate(reader):
            user_name = row['username']
            if _validate_user(user_name):
                User.objects.get_or_create(
                    username=row['username'],
                    password='password',
                )
                print("User added")
            else:
                print("Invaid user")

when i run the code using python3 manage.py shell and input code line by line i'm not getting any error and everything is working as expected.

When i use python3 manage.py shell < utility_folder/load_users.py to run the script i'm getting NameError: name 'urllib3' is not defined at line number 6. What am i missing here. I tried with requests module also didn't do much help.

Django version is 1.11 and python 3.6

Please advice.

1 Answer 1

4

Use exec(open("utility_folder/load_users.py").read()) into the shell instead of python3 manage.py shell < utility_folder/load_users.py.

Sign up to request clarification or add additional context in comments.

2 Comments

If you're going to do this more than once, consider creating a Django management command.
This is working, do you have any idea why the conventional way is not working ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.