求助:跟随graphene-python官方教程无法导入cookbook.schema.schema
Hey there! I’ve run into this exact schema import snag countless times when walking through the graphene-python cookbook—let’s break down what’s probably going wrong and how to fix it.
First, Double-Check Your Project Structure
The most common culprit here is a misaligned project structure that breaks Python’s import system. Your setup should look something like this (pay close attention to the nested cookbook folder and __init__.py):
your-project-root/ ├── cookbook/ # This is your Django project folder │ ├── __init__.py # Critical! Makes this a Python package │ ├── settings.py # Where your GRAPHENE config lives │ └── schema.py # Your graphene schema file └── manage.py
If the inner cookbook folder doesn’t have an __init__.py file, Python won’t recognize it as an importable package—create one (it can be completely empty) right away.
Verify Your Schema Configuration & Code
1. Confirm the GRAPHENE Setting in settings.py
Your current config looks right on paper, but let’s make sure it’s pointing to the correct Python path:
GRAPHENE = { 'SCHEMA': 'cookbook.schema.schema' }
This translates to: "Look in the cookbook package, then the schema module, then grab the schema variable."
2. Check That schema.py Defines a schema Variable
Open your schema.py and make sure you’ve actually created the schema instance at the bottom (or somewhere accessible):
import graphene # Your query/mutation definitions here, e.g.: class Query(graphene.ObjectType): hello = graphene.String(default_value="Hello world!") # This line is essential—without it, there's no `schema` to import! schema = graphene.Schema(query=Query)
If you’re missing that final schema = graphene.Schema(...) line, Django/graphene won’t find what it’s looking for.
Troubleshooting Further
If the above steps don’t fix it, try these quick checks:
- Run
python manage.py shelland test the import manually:
If this throws an error, the traceback will tell you exactly where the problem is (e.g., missing dependencies, syntax errors infrom cookbook.schema import schema print(schema)schema.py). - Make sure your virtual environment is activated (if you’re using one)—sometimes packages are installed globally but not in your venv, causing import issues.
- Double-check for typos: Is it
cookbook.schema.schemaor did you accidentally writecookbook.Schema.schema(capital S)? Small typos break everything!
内容的提问来源于stack exchange,提问作者Chad Van De Hey

