I need to run this code but I find this error:
Traceback (most recent call last):
File "C:\Users\DELL\Downloads\snapArt.py", line 1, in <module>
import requests
ModuleNotFoundError: No module named 'requests'
Code:
import requests
from hashlib import sha256
from time import time, sleep
print("""
""")
FielUser = open('Users.txt' , 'r').read().splitlines()
req = requests.session()
def token():
for i, c in enumerate("0001110111101110001111010101111011010001001110011000110001000110"):
if c == "0":
yield sha256(("iEk21fuwZApXlz93750dmW22pw389dPwOk"+"m198sOkJEn37DjqZ32lpRu76xmw288xSQ9").encode('utf-8')).hexdigest()[i]
else:
yield sha256((str(int(round(time() * 1000.0))) + "iEk21fuwZApXlz93750dmW22pw389dPwOk").encode('utf-8')).hexdigest()[i]
for user in FielUser:
if user:
user = user.strip()
url = 'https://app.snapchat.com/loq/suggest_username_v2'
headers = {'User-Agent':'Snapchat/10.25.0.0 (Agile_Client_Error; Android 5.1.1#500181103#22; gzip)'}
data = {
'req_token': "".join(list(token())),
'requested_username': user,
'timestamp': int(round(time() * 1000.0)),
'status_code': ''
}
res = req.post(url, headers=headers, data=data)
if res:
JSON = res.json()
#print(JSON)
if JSON.get('requested_username') and JSON.get('status_code') == 'OK':
with open('Found.txt', "a+") as file_save:
file_save.write(user + '\n')
print('available ->', user)
sleep(1)
else:
print('not available ->', user)
sleep(1)
print('''
''')
Be sure you are not in a virtual environment (venv). This could be one of your issues.
You would not have installed the module called requests. To do that simply open your cmd (command prompt) or terminal and type pip install requests.
Related
I want to import a file in a local directory but python refused to do so and it gives error everytime i do so.
I tried putting "from Admin_login import Admin_login" but it gives an error saying
"ModuleNotFoundError: No module named 'Admin_login'"
my code:-(main.py)
from .Admin_login import Admin_login
loggsin = Admin_login.login()
if loggsin == True:
print("You are logged in")
This is the Admin_login.py file
import json
import os
def load_data():
with open("data.json", "r") as f:
Data = json.load(f)
return Data
class Admin_login():
def login(self):
Login = False
while Login == False:
id = input("Enter the id you want to login = ")
data = load_data()
if id == data["id"]:
print(data["name"])
passord = input("Enter the password = ")
if passord == data["password"]:
print("You are successfully logged in")
Login = True
return Login
os.system('cls')
else:
print("The id doesn't exist... Please try again!")
Login = False
return Login
os.system('cls')
if __name__ == '__main__' :
Admin_login()
and the error it gives is :-
Traceback (most recent call last):
File "C:\Users\myUser\Desktop\LibApp\main.py", line 1, in <module>
from .Admin_login import Admin_login
ImportError: attempted relative import with no known parent package
pls help
My best guess is that the '.' is giving you the trouble. When you add a dot to a directory name, it is referring to a relative directory and not an absolute one. That's what that error you're getting is referring to. If those two files are in the same directory, you can just remove the dot and it should work.
I'm trying to get the generated domain name or IP-address of flask_ngrok or py-ngrok after been deploy. I want to deploy flask_app to localhost and get the new IP-address or domain name on the main page.
I.E: If I access 127.0.0.1/ I want it to return something like
You can now log in through https://aaf8447ee878.ngrok.io/
I have tried checking through the directories and read some help but I can't still get it. Thanks in advance ❤
add
import atexit
import json
import os
import platform
import shutil
import subprocess
import tempfile
import time
import zipfile
from pathlib import Path
from threading import Timer
import requests
def _run_ngrok():
ngrok_path = str(Path(tempfile.gettempdir(), "ngrok"))
_download_ngrok(ngrok_path)
system = platform.system()
if system == "Darwin":
command = "ngrok"
elif system == "Windows":
command = "ngrok.exe"
elif system == "Linux":
command = "ngrok"
else:
raise Exception(f"{system} is not supported")
executable = str(Path(ngrok_path, command))
os.chmod(executable, 777)
ngrok = subprocess.Popen([executable, 'http', '5000'])
atexit.register(ngrok.terminate)
localhost_url = "http://localhost:4040/api/tunnels" # Url with tunnel details
time.sleep(1)
tunnel_url = requests.get(localhost_url).text # Get the tunnel information
j = json.loads(tunnel_url)
tunnel_url = j['tunnels'][0]['public_url'] # Do the parsing of the get
tunnel_url = tunnel_url.replace("https", "http")
return tunnel_url
def _download_ngrok(ngrok_path):
if Path(ngrok_path).exists():
return
system = platform.system()
if system == "Darwin":
url = "https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-darwin-amd64.zip"
elif system == "Windows":
url = "https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-windows-amd64.zip"
elif system == "Linux":
url = "https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip"
else:
raise Exception(f"{system} is not supported")
download_path = _download_file(url)
with zipfile.ZipFile(download_path, "r") as zip_ref:
zip_ref.extractall(ngrok_path)
def _download_file(url):
local_filename = url.split('/')[-1]
r = requests.get(url, stream=True)
download_path = str(Path(tempfile.gettempdir(), local_filename))
with open(download_path, 'wb') as f:
shutil.copyfileobj(r.raw, f)
return download_path
def start_ngrok():
global ngrok_address
ngrok_address = _run_ngrok()
print(f" * Running on {ngrok_address}")
print(f" * Traffic stats available on http://127.0.0.1:4040")
def run_with_ngrok(app):
"""
The provided Flask app will be securely exposed to the public internet via ngrok when run,
and the its ngrok address will be printed to stdout
:param app: a Flask application object
:return: None
"""
old_run = app.run
def new_run():
thread = Timer(1, start_ngrok)
thread.setDaemon(True)
thread.start()
old_run()
app.run = new_run
####################
dont import flask_ngrok
at the end at before name == 'main' add this function
def ngrok_url():
global tunnel_url
while True:
try:
print(ngrok_address)
except Exception as e:
print(e)
and after before app.run() put
thread = Timer(1, ngrok_url)
thread.setDaemon(True)
thread.start()
and run Warning: this will crash your code editor/ or terminal if u dont want that in the ngrok url function replace print with whatever you want to do with the url
and you dont need that
global tunnel_url
def ngrok_url():
while True:
try:
print(ngrok_address)
except Exception as e:
print(e)
you can delete the threading part before the name == 'main' too after the imports set
ngrok_address = ''
then you can accses the ngrok_address anywhere in your code
I found out the easiest way to do this is the just copy the url when the user is visiting the site. You can do this by...
#app.before_request
def before_request():
global url
url = request.url
# url = url.replace('http://', 'https://', 1)
url = url.split('.ngrok.io')[0]
url += '.ngrok.io'
pyzabbix is a module needed for this script to work. I installed it using pip, please see a confirmation below:
WARNING: The script chardetect.exe is installed in 'C:\Users\Christopher Ezimoha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\Scripts' which is not on PATH.
Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed certifi-2019.11.28 chardet-3.0.4 idna-2.8 pyzabbix-0.7.5 requests-2.22.0 urllib3-1.25.8
C:\Users\Christopher Ezimoha\Desktop>
However, I'm getting an error at line 24 that the module can't be found. I'm not sure what I need to do.
Please see the script below and advise accordingly as I need this code to read a CSV file and update an application called Zabbix.
def addHosts(zapi):
# Add Hosts
file = open('hosts.csv', 'r')
reader = csv.reader(file)
devicelist = list(reader)
import csv
def login():
# Login/authenticate below
session = ZabbixAPI('https://zabbix.xxxxxx.xxx')
# session = ZabbixAPI('http://xxxxxxxxxx/zabbix')
session.login(user="xxxxxxxxxxxx", password="xxxxxxxx")
print("Connected to Zabbix API Version %s" % session.api_version())
return session
for row in devicelist:
device = row[0]
hostgroup = row[1]
responsegroup = zapi.hostgroup.get(filter={'name': hostgroup})
groupid = responsegroup[0]['groupid']
ip = row[2]
templatePriority = row[3]
responsepriority = zapi.template.get(filter={'name': templatePriority})
templatePriorityId = responsepriority[0]['templateid']
# if templatePriority == 'P1':
# templatePriorityId = '40874'
templateType = row[4]
responsetype = zapi.template.get(filter={'name': templateType})
templateTypeId = responsetype[0]['templateid']
try:
response = zapi.host.create(
host=device,
interfaces=[{
'type': 2,
'main': 1,
'ip': ip,
'dns': '',
'port': 161,
'useip': 1
}],
groups=[{
'groupid': groupid}],
templates=[{'templateid': templatePriorityId}, {'templateid': templateTypeId}],
inventory_mode=1
)
print("Created new host: " + device)
except ZabbixAPIException as e:
if 'already exists' in e[0]:
print("Already created host " + device)
else:
print(e[0])
return
def main():
# hostgroup = raw_input('Hostgroup: ')
#hostgroup = "ALTC - Altcar"
zapi = login()
addHosts(zapi)
return
if __name__ == '__main__':
main()
Do you have both python 2 and 3 installed? If you have both, pip installs modules under python2. Try installing like this if you'd like the module to be installed under python3:
pip3 install pyzabbix
There is no import, in the code you included in the question:
from pyzabbix import ZabbixAPI
The login() function should be defined outside of addHosts(), in order to be called like that in main()
I'm trying to write a web parser script using requests module. Here is my current code:
import requests
import subprocess
import json
import sys
import threading
import time
from Queue import Queue
numberOfViewers = int(sys.argv[1])
builderThreads = int(sys.argv[2])
startTime = time.time()
numberOfSockets = 0
concurrent = 25
urls = []
urlsUsed = []
def getURL(): # Get tokens
output = subprocess.Popen(["livestreamer", "twitch.tv/CHANNEL_NAME", "-j"],
stdout=subprocess.PIPE).communicate()[0]
return json.loads(output)['streams']['worst']['url'] # Parse json and return the URL parameter
def build(): # Builds a set of tokens, aka viewers
global numberOfSockets
global numberOfViewers
while True:
if numberOfSockets < numberOfViewers:
numberOfSockets += 1
print ("Building viewers " + str(numberOfSockets) + "/" + str(numberOfViewers))
urls.append(getURL())
def view(): # Opens connections to send views
global numberOfSockets
while True:
url=q.get()
requests.head(url)
if (url in urlsUsed):
urls.remove(url)
urlsUsed.remove(url)
numberOfSockets -= 1
else:
urlsUsed.append(url)
q.task_done()
if __name__ == '__main__':
for i in range(0, builderThreads):
threading.Thread(target = build).start()
while True:
while (numberOfViewers != numberOfSockets): # Wait until sockets are built
time.sleep(1)
q=Queue(concurrent*2)
for i in range(concurrent):
try:
t=threading.Thread(target=view)
t.daemon=True
t.start()
except:
print ('thread error')
try:
for url in urls:
print (url)
q.put(url.strip())
q.join()
except KeyboardInterrupt:
sys.exit(1)
But when I run the code, it says:
Traceback (most recent call last):
File "C:\Users\flamelier\Desktop\Twitch.py", line 1, in <module>
import requests
ImportError: No module named 'requests'
Why am I getting this error? How do I install this module?
Will this error keep repeating for all the scripts henceforth?
How can I prevent such similar errors in the future?
Requests is a 3rd party module. You should first install it to Python using PIP or easy_install.
You have to run pip3 install requests as requests doesn't come with Python by default, as it is a third party library.
Even after you have pip3-installed requests, the code shown won't do anything. The
if __name__ == "__main__"
test and everything after it is part of an else block in the view function. Back this line and the block that follows out to the left margin.
I got this error when run test.py
C:\Python32>python.exe test.py
Traceback (most recent call last):
File "test.py", line 5, in <module>
import httplib
ImportError: No module named httplib
How to correct it?
Code block for test.py:
#!/usr/local/bin/python
import httplib
import sys
import re
from HTMLParser import HTMLParser
class miniHTMLParser( HTMLParser ):
viewedQueue = []
instQueue = []
def get_next_link( self ):
if self.instQueue == []:
return ''
else:
return self.instQueue.pop(0)
def gethtmlfile( self, site, page ):
try:
httpconn = httplib.HTTPConnection(site)
httpconn.request("GET", page)
resp = httpconn.getresponse()
resppage = resp.read()
except:
resppage = ""
return resppage
def handle_starttag( self, tag, attrs ):
if tag == 'a':
newstr = str(attrs[0][1])
if re.search('http', newstr) == None:
if re.search('mailto', newstr) == None:
if re.search('htm', newstr) != None:
if (newstr in self.viewedQueue) == False:
print (" adding", newstr)
self.instQueue.append( newstr )
self.viewedQueue.append( newstr )
else:
print (" ignoring", newstr)
else:
print (" ignoring", newstr)
else:
print (" ignoring", newstr)
def main():
if sys.argv[1] == '':
print ("usage is ./minispider.py site link")
sys.exit(2)
mySpider = miniHTMLParser()
link = sys.argv[2]
while link != '':
print ("\nChecking link ", link)
# Get the file from the site and link
retfile = mySpider.gethtmlfile( sys.argv[1], link )
# Feed the file into the HTML parser
mySpider.feed(retfile)
# Search the retfile here
# Get the next link in level traversal order
link = mySpider.get_next_link()
mySpider.close()
print ("\ndone\n")
if __name__ == "__main__":
main()
You are running Python 2 code on Python 3. In Python 3, the module has been renamed to http.client.
You could try to run the 2to3 tool on your code, and try to have it translated automatically. References to httplib will automatically be rewritten to use http.client instead.
you can just import http.client and rename it to httplib with this code :
import http.client as httplib
If you use PyCharm, please change you 'Project Interpreter' to '2.7.x'
I had this issue when I was trying to make my Docker container smaller. It was because I'd installed Python 2.7 with:
apt-get install -y --no-install-recommends python
And I should not have included the --no-install-recommends flag:
apt-get install -y python